-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy patherrors.ts
More file actions
50 lines (46 loc) · 1.49 KB
/
errors.ts
File metadata and controls
50 lines (46 loc) · 1.49 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
import { ZodError, z } from 'zod';
import { UNICODE_ELLIPSIS, truncateMultilineText } from './formatting.js';
export function stringifyError(
error: unknown,
format?: { oneline: boolean },
): string {
const truncate = (text: string) =>
format?.oneline ? truncateMultilineText(text) : text;
if (error instanceof ZodError) {
const formattedError = z.prettifyError(error);
if (formattedError.includes('\n')) {
if (format?.oneline) {
return `${error.name} [${UNICODE_ELLIPSIS}]`;
}
return `${error.name}:\n${formattedError}\n`;
}
return `${error.name}: ${formattedError}`;
}
if (error instanceof Error) {
if (error.name === 'Error' || error.message.startsWith(error.name)) {
return truncate(error.message);
}
return truncate(`${error.name}: ${error.message}`);
}
if (typeof error === 'string') {
return truncate(error);
}
return JSON.stringify(error);
}
/**
* Extends an error with a new message and keeps the original as the cause.
* This helps to keep the stacktrace intact and enables better debugging.
* @param error - The error to extend
* @param message - The new message to add to the error
* @returns A new error with the extended message and the original as cause
*/
export function extendError(
error: unknown,
message: string,
{ appendMessage = false } = {},
) {
const errorMessage = appendMessage
? `${message}\n${stringifyError(error)}`
: message;
return new Error(errorMessage, { cause: error });
}