-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy patherrorUtils.ts
More file actions
58 lines (51 loc) · 1.44 KB
/
errorUtils.ts
File metadata and controls
58 lines (51 loc) · 1.44 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
import { isApiError, isApiErrorResponse } from "coder/site/src/api/errors";
import util from "node:util";
/**
* Check whether an unknown thrown value is an AbortError (signal cancellation).
*/
export function isAbortError(error: unknown): boolean {
return error instanceof Error && error.name === "AbortError";
}
// getErrorDetail is copied from coder/site, but changes the default return.
export const getErrorDetail = (error: unknown): string | undefined | null => {
if (isApiError(error)) {
return error.response.data.detail;
}
if (isApiErrorResponse(error)) {
return error.detail;
}
return null;
};
/**
* Convert any value into an Error instance.
* Handles Error instances, strings, error-like objects, null/undefined, and primitives.
*/
export function toError(value: unknown, defaultMsg?: string): Error {
if (value instanceof Error) {
return value;
}
if (typeof value === "string") {
return new Error(value);
}
if (
value !== null &&
typeof value === "object" &&
"message" in value &&
typeof value.message === "string"
) {
const error = new Error(value.message);
if ("name" in value && typeof value.name === "string") {
error.name = value.name;
}
return error;
}
if (value === null || value === undefined) {
return new Error(defaultMsg || "Unknown error");
}
try {
return new Error(util.inspect(value));
} catch {
// Just in case
return new Error(defaultMsg || "Non-serializable error object");
}
}