feat(httpRequest): add error body parsing
This commit is contained in:
parent
12884e0242
commit
3d8980f686
1 changed files with 36 additions and 16 deletions
|
@ -61,11 +61,15 @@ export function delegate<E extends Event = Event>(
|
||||||
}
|
}
|
||||||
|
|
||||||
export class ResponseError extends Error {
|
export class ResponseError extends Error {
|
||||||
response: Response;
|
readonly response: Response;
|
||||||
|
readonly jsonBody?: unknown;
|
||||||
|
readonly textBody?: string;
|
||||||
|
|
||||||
constructor(response: Response) {
|
constructor(response: Response, jsonBody?: unknown, textBody?: string) {
|
||||||
super(String(response.statusText || response.status));
|
super(String(response.statusText || response.status));
|
||||||
this.response = response;
|
this.response = response;
|
||||||
|
this.jsonBody = jsonBody;
|
||||||
|
this.textBody = textBody;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -125,26 +129,42 @@ export function httpRequest(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const request = (init: RequestInit, accept?: string): Promise<Response> => {
|
const request = async (
|
||||||
|
init: RequestInit,
|
||||||
|
accept?: string
|
||||||
|
): Promise<Response> => {
|
||||||
if (accept && init.headers instanceof Headers) {
|
if (accept && init.headers instanceof Headers) {
|
||||||
init.headers.set('accept', accept);
|
init.headers.set('accept', accept);
|
||||||
}
|
}
|
||||||
return fetch(url, init)
|
try {
|
||||||
.then((response) => {
|
const response = await fetch(url, init);
|
||||||
clearTimeout(timer);
|
|
||||||
|
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
return response;
|
return response;
|
||||||
} else if (response.status == 401) {
|
} else if (response.status == 401) {
|
||||||
location.reload(); // reload whole page so Devise will redirect to sign-in
|
location.reload(); // reload whole page so Devise will redirect to sign-in
|
||||||
}
|
}
|
||||||
throw new ResponseError(response);
|
|
||||||
})
|
const contentType = response.headers.get('content-type');
|
||||||
.catch((error) => {
|
let jsonBody: unknown;
|
||||||
|
let textBody: string | undefined;
|
||||||
|
try {
|
||||||
|
if (contentType?.match('json')) {
|
||||||
|
jsonBody = await response.json();
|
||||||
|
} else {
|
||||||
|
textBody = await response.text();
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
throw new ResponseError(response, jsonBody, textBody);
|
||||||
|
} catch (error) {
|
||||||
clearTimeout(timer);
|
clearTimeout(timer);
|
||||||
|
|
||||||
throw error;
|
throw error;
|
||||||
});
|
} finally {
|
||||||
|
clearTimeout(timer);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|
Loading…
Reference in a new issue