errors: avoid [object Object] as cause + fix ForwardedError name

Signed-off-by: Patrik Oldsberg <poldsberg@gmail.com>
This commit is contained in:
Patrik Oldsberg
2021-10-16 15:12:18 +02:00
parent 36e67d2f24
commit 381381bd2b
3 changed files with 21 additions and 2 deletions
@@ -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}'`;
}
+15 -1
View File
@@ -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',
);
});
});
+1 -1
View File
@@ -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';
}
}