2021-10-26 16:17:24 +00:00
|
|
|
export function getErrorFromUnknown(cause: unknown): Error & { statusCode?: number; code?: string } {
|
2021-10-20 15:42:40 +00:00
|
|
|
if (cause instanceof Error) {
|
|
|
|
return cause;
|
|
|
|
}
|
|
|
|
if (typeof cause === "string") {
|
|
|
|
// @ts-expect-error https://github.com/tc39/proposal-error-cause
|
|
|
|
return new Error(cause, { cause });
|
|
|
|
}
|
|
|
|
|
|
|
|
return new Error(`Unhandled error of type '${typeof cause}''`);
|
|
|
|
}
|
2021-10-26 16:17:24 +00:00
|
|
|
|
2022-10-31 22:06:03 +00:00
|
|
|
export async function handleErrorsJson<Type>(response: Response): Promise<Type> {
|
2022-07-27 19:12:42 +00:00
|
|
|
if (response.headers.get("content-encoding") === "gzip") {
|
2022-10-31 22:06:03 +00:00
|
|
|
const responseText = await response.text();
|
|
|
|
return new Promise((resolve) => resolve(JSON.parse(responseText)));
|
2022-07-27 19:12:42 +00:00
|
|
|
}
|
2022-10-31 22:06:03 +00:00
|
|
|
|
2022-07-20 20:02:00 +00:00
|
|
|
if (response.status === 204) {
|
2022-10-31 22:06:03 +00:00
|
|
|
return new Promise((resolve) => resolve({} as Type));
|
2022-07-20 20:02:00 +00:00
|
|
|
}
|
2022-10-31 22:06:03 +00:00
|
|
|
|
2022-07-20 20:02:00 +00:00
|
|
|
if (!response.ok && response.status < 200 && response.status >= 300) {
|
2021-10-26 16:17:24 +00:00
|
|
|
response.json().then(console.log);
|
|
|
|
throw Error(response.statusText);
|
|
|
|
}
|
2022-07-27 19:12:42 +00:00
|
|
|
|
2021-10-26 16:17:24 +00:00
|
|
|
return response.json();
|
|
|
|
}
|
|
|
|
|
|
|
|
export function handleErrorsRaw(response: Response) {
|
2022-07-20 20:02:00 +00:00
|
|
|
if (response.status === 204) {
|
2022-11-18 17:41:36 +00:00
|
|
|
console.error({ response });
|
2022-07-21 09:59:37 +00:00
|
|
|
return "{}";
|
2022-07-20 20:02:00 +00:00
|
|
|
}
|
|
|
|
if (!response.ok && response.status < 200 && response.status >= 300) {
|
2021-10-26 16:17:24 +00:00
|
|
|
response.text().then(console.log);
|
|
|
|
throw Error(response.statusText);
|
|
|
|
}
|
|
|
|
return response.text();
|
|
|
|
}
|