-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.ts
More file actions
59 lines (47 loc) · 1.82 KB
/
errors.ts
File metadata and controls
59 lines (47 loc) · 1.82 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
import { globalConfig } from 'f61ui/globalconfig';
import { StructuredErrorResponse } from 'f61ui/types';
export function defaultErrorHandler(err: Error | StructuredErrorResponse) {
const ser = coerceToStructuredErrorResponse(err);
if (handleKnownGlobalErrors(ser)) {
return;
}
alert(formatStructuredErrorResponse(ser));
}
export function formatStructuredErrorResponse(ser: StructuredErrorResponse): string {
if (ser.error_code === 'generic') {
// means pretty much "unknown", so no sense in showing it
return ser.error_description;
}
return `${ser.error_code}: ${ser.error_description}`;
}
export function formatAnyError(err: Error | StructuredErrorResponse): string {
return formatStructuredErrorResponse(coerceToStructuredErrorResponse(err));
}
export function handleKnownGlobalErrors(err: StructuredErrorResponse): boolean {
const handler = globalConfig().knownGlobalErrorsHandler;
if (!handler) {
return false;
}
return handler(err);
}
export function coerceToStructuredErrorResponse(
err: Error | StructuredErrorResponse,
): StructuredErrorResponse {
if (isStructuredErrorResponse(err)) {
return err;
}
return { error_code: 'generic', error_description: err.toString() };
}
export function isStructuredErrorResponse(
err: StructuredErrorResponse | {},
): err is StructuredErrorResponse {
return typeof err === 'object' && 'error_code' in (err as StructuredErrorResponse);
}
// not all caught errors inherit from `Error` (which would have `.toString()` available which we likely need).
// most likely they do, but this function "coerces" everything to `Error` even if it means losing
// original object in entirety (because it's just unlikely anyway).
export function asError(possiblyError: any): Error {
return possiblyError instanceof Error
? possiblyError
: new Error('given variable not instance of Error');
}