forked from equinor/flotilla
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApiError.tsx
More file actions
79 lines (73 loc) · 2.45 KB
/
Copy pathApiError.tsx
File metadata and controls
79 lines (73 loc) · 2.45 KB
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
72
73
74
75
76
77
78
79
import { CustomError } from 'ts-custom-error'
const StatusTexts: { [key: number]: string } = {
400: 'Bad Request',
401: 'Unauthorized', // RFC 7235
402: 'Payment Required',
403: 'Forbidden',
404: 'Not Found',
405: 'Method Not Allowed',
406: 'Not Acceptable',
407: 'Proxy Authentication Required', // RFC 7235
408: 'Request Timeout',
409: 'Conflict',
410: 'Gone',
411: 'Length Required',
412: 'Precondition Failed', // RFC 7232
413: 'Payload Too Large', // RFC 7231
414: 'URI Too Long', // RFC 7231
415: 'Unsupported Media Type',
416: 'Range Not Satisfiable', // RFC 7233
417: 'Expectation Failed',
418: "I'm a teapot", // RFC 2324
421: 'Misdirected Request', // RFC 7540
426: 'Upgrade Required',
428: 'Precondition Required', // RFC 6585
429: 'Too Many Requests', // RFC 6585
431: 'Request Header Fields Too Large', // RFC 6585
451: 'Unavailable For Legal Reasons', // RFC 7725
500: 'Internal Server Error',
501: 'Not Implemented',
502: 'Bad Gateway',
503: 'Service Unavailable',
504: 'Gateway Timeout',
505: 'HTTP Version Not Supported',
506: 'Variant Also Negotiates', // RFC 2295
510: 'Not Extended', // RFC 2774
511: 'Network Authentication Required', // RFC 6585
} as const
/**
* Api error
*
* Usage: throw ApiError.fromCode(404)
*/
export class ApiError extends CustomError {
public constructor(
public statusCode: number,
public message: string,
public logMessage: string
) {
super(logMessage)
}
public static fromCode(code: number, statusText?: string, message?: string) {
if (!Object.keys(StatusTexts).includes(String(code))) code = 400
statusText = statusText ?? StatusTexts[code]
if (code >= 400 && code < 500) return new ApiError(code, message ?? statusText, `${code} - ${statusText}`)
else
return new ApiError(
code,
'An unexpected error occured when handling the request',
`${code} - ${statusText}`
)
}
}
function isApiError(err: any): err is ApiError {
return err instanceof ApiError
}
export const handleError = (requestType: string, path: string) => (e: unknown) => {
if (isApiError(e)) {
console.error('Failed to %s /%s: %s', requestType, path, e.message)
throw new Error(e.message)
}
console.error('Failed to %s /%s:', requestType, path, e)
throw e
}