Skip to content

Commit b4f47f2

Browse files
committed
refactor: improve error handling in normalizeError and getErrorMessage functions
1 parent cb6e994 commit b4f47f2

1 file changed

Lines changed: 16 additions & 12 deletions

File tree

src/common/error.ts

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,28 +5,32 @@ import { stringify } from "./json";
55
export const normalizeError = (error: unknown, caller?: Function): Error => {
66
if (isError(error)) return error;
77

8-
let message: string;
8+
const e = new Error(getErrorMessage(error));
9+
Error.captureStackTrace(e, caller || normalizeError);
10+
11+
return e;
12+
};
13+
14+
export const getErrorMessage = (error: unknown, message?: string): string => {
15+
if (isError(error)) return error.message;
16+
if (message !== undefined) return message;
17+
18+
let msg: string;
919
if (
1020
isString(error) ||
1121
isNumber(error) ||
1222
isBigInt(error) ||
1323
isBoolean(error) ||
1424
isSymbol(error)
1525
) {
16-
message = error.toString();
26+
msg = error.toString();
1727
} else if (error === undefined) {
18-
message = "undefined";
28+
msg = "undefined";
1929
} else if (error === null) {
20-
message = "null";
30+
msg = "null";
2131
} else {
22-
message = stringify(error);
32+
msg = stringify(error);
2333
}
2434

25-
const e = new Error(message);
26-
Error.captureStackTrace(e, caller || normalizeError);
27-
28-
return e;
35+
return msg;
2936
};
30-
31-
export const getErrorMessage = (error: unknown, message = "Unknown error"): string =>
32-
error instanceof Error ? error.message : message;

0 commit comments

Comments
 (0)