Skip to content

Commit 2090524

Browse files
committed
fix: nested error causes sometimes serialized incorrectly resulting in "Object" as message
1 parent 23c5e3b commit 2090524

2 files changed

Lines changed: 18 additions & 15 deletions

File tree

lib/custom-error.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -226,12 +226,13 @@ export class CustomError extends Error {
226226
status: this.status,
227227
...(this.details && { details: this.details }),
228228
...(this.cause instanceof Error && {
229-
cause: CustomError.isCustomError(this.cause)
230-
? this.cause.toJSON()
231-
: {
232-
message: this.cause.message,
233-
name: 'Error',
234-
},
229+
cause:
230+
'toJSON' in this.cause && typeof this.cause.toJSON === 'function'
231+
? this.cause.toJSON()
232+
: {
233+
message: this.cause.message,
234+
name: 'Error',
235+
},
235236
}),
236237
...(this.stack && { stack: this.stack }),
237238
...(debug && { debug }),

lib/serialize.ts

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ export interface SerializedError {
66
message: string;
77
statusCode?: number;
88
stack?: string;
9-
cause?: SerializedError[];
9+
cause?: SerializedError[] | unknown;
1010

1111
[key: string]: unknown;
1212
}
@@ -15,13 +15,13 @@ function flattenPreviousErrors(
1515
err: Error | CustomError | unknown,
1616
accum: (Error | CustomError)[] = [],
1717
): (Error | CustomError)[] {
18-
if (CustomError.isCustomError(err)) {
19-
const { cause, ...rest } = err;
20-
return flattenPreviousErrors(cause, [...accum, rest]);
21-
}
2218
if (err instanceof Error) {
19+
if ('cause' in err && err.cause) {
20+
return flattenPreviousErrors(err.cause, [...accum, err]);
21+
}
2322
return [...accum, err];
2423
}
24+
2525
return accum;
2626
}
2727

@@ -30,23 +30,25 @@ export function serializeError(
3030
): SerializedError {
3131
if (CustomError.isCustomError(err)) {
3232
const previousErrors =
33-
'cause' in err && err.cause ? flattenPreviousErrors(err.cause) : [];
33+
'cause' in err && err.cause
34+
? flattenPreviousErrors(err.cause)
35+
: undefined;
3436

3537
return {
3638
...serialize(err),
3739
message: err.message,
3840
name: err.name,
3941
status: err.status,
40-
cause: previousErrors.map(serializeError),
41-
...('debug' in err ? { debug: err.debug() } : {}),
42+
...(previousErrors && { cause: previousErrors.map(serializeError) }),
43+
...('debug' in err && { debug: err.debug() }),
4244
};
4345
}
4446

4547
if (err instanceof Error) {
4648
const { name, message, stack, cause, code, ...debug } = serialize(err);
4749

4850
return {
49-
message: message || '',
51+
message: message || 'Error',
5052
name: name || 'Error',
5153
code,
5254
stack,

0 commit comments

Comments
 (0)