errors: avoid [object Object] as cause + fix ForwardedError name
Signed-off-by: Patrik Oldsberg <poldsberg@gmail.com>
This commit is contained in:
@@ -29,6 +29,11 @@ export class CustomErrorBase extends Error {
|
||||
if (isError(cause)) {
|
||||
assignedCause = cause;
|
||||
causeStr = String(cause);
|
||||
|
||||
// Prefer the cause.toString, but if it's not implemented we use a nicer fallback
|
||||
if (causeStr === '[object Object]') {
|
||||
causeStr = `${cause.name}: ${cause.message}`;
|
||||
}
|
||||
} else {
|
||||
causeStr = `unknown error '${cause}'`;
|
||||
}
|
||||
|
||||
@@ -31,12 +31,26 @@ describe('common', () => {
|
||||
|
||||
it('supports causes', () => {
|
||||
const cause = new Error('hello');
|
||||
for (const [name, E] of Object.entries(errors)) {
|
||||
const { ForwardedError, ...otherErrors } = { ...errors };
|
||||
for (const [name, E] of Object.entries(otherErrors)) {
|
||||
const error = new E('abcdef', cause);
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error.toString()).toContain(
|
||||
`${name}: abcdef; caused by Error: hello`,
|
||||
);
|
||||
}
|
||||
|
||||
const error = new ForwardedError('abcdef', cause);
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error.toString()).toContain('Error: abcdef; caused by Error: hello');
|
||||
});
|
||||
|
||||
it('avoids [object Object]', () => {
|
||||
const cause = { name: 'SillyError', message: 'oh no' };
|
||||
const error = new errors.ForwardedError('abcdef', cause);
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(String(error)).toBe(
|
||||
'SillyError: abcdef; caused by SillyError: oh no',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -86,6 +86,6 @@ export class ForwardedError extends CustomErrorBase {
|
||||
constructor(message: string, cause: Error | unknown) {
|
||||
super(message, cause);
|
||||
|
||||
this.name = isError(cause) ? this.constructor.name : 'Error';
|
||||
this.name = isError(cause) ? cause.name : 'Error';
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user