-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetErrorMessageFromResponse.ts
71 lines (63 loc) · 2.17 KB
/
getErrorMessageFromResponse.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
const getBodyMessage = (body: unknown): string | false =>
!!(!!body && typeof body === "object" && "message" in body && typeof body.message === "string") &&
body.message;
const getErrorsMessage = (body: unknown): string | false =>
!!(!!body && typeof body === "object" && "errors" in body && Array.isArray(body.errors)) &&
`\
Errors:
${body.errors.map((err) => `- ${getBodyMessage(err)}`).join("\n")}`;
const getErrorMessage = (body: unknown): string | false =>
!!(
!!body &&
typeof body === "object" &&
"error" in body &&
!!body.error &&
typeof body.error === "object" &&
"message" in body.error &&
typeof body.error.message === "string"
) && body.error.message;
const getDataMessage = (
body: unknown,
{ parseDevalue }: { parseDevalue: (str: string) => unknown },
): string | false => {
if (!(!!body && typeof body === "object" && "data" in body && typeof body.data === "string")) {
return false;
}
try {
const parsed: unknown = parseDevalue(body.data);
if (
!(
!!parsed &&
typeof parsed === "object" &&
"message" in parsed &&
typeof parsed.message === "string"
)
) {
return false;
}
return parsed.message;
} catch (_) {
return false;
}
};
export default async (response: Response): Promise<string | undefined> => {
const { parse: parseDevalue } = await import("devalue");
const contentType = response.headers.get("Content-Type");
if (!contentType) return;
if (contentType.startsWith("text/plain")) return response.text();
if (contentType.startsWith("application/json") || contentType.startsWith("text/json")) {
const body = await response.json();
// Error message from Contentful
const bodyMessage = getBodyMessage(body);
if (bodyMessage) return bodyMessage;
// List of errors from Contentful
const errorsMessage = getErrorsMessage(body);
if (errorsMessage) return errorsMessage;
// Error message from SvelteKit
const dataMessage = getDataMessage(body, { parseDevalue });
if (dataMessage) return dataMessage;
// Generic error message
return getErrorMessage(body) || "(unknown error message)";
}
return undefined;
};