Skip to content

Commit 724ddd8

Browse files
committed
Make errors serializable by default
1 parent acbeb1c commit 724ddd8

2 files changed

Lines changed: 37 additions & 0 deletions

File tree

packages/common/exceptions/http.exception.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,18 @@ export class HttpException extends Error {
3030
public getStatus(): number {
3131
return this.status;
3232
}
33+
34+
private getError(target) {
35+
if(typeof target === 'string') {
36+
return target;
37+
}
38+
39+
return JSON.stringify(target);
40+
}
41+
42+
public toString(): string {
43+
const message = this.getError(this.message);
44+
45+
return `Error: ${message}`;
46+
}
3347
}

packages/common/test/exceptions/http.exception.spec.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,4 +44,27 @@ describe('HttpException', () => {
4444
statusCode: 404,
4545
});
4646
});
47+
48+
it('Should inherit from error', () => {
49+
const error = new HttpException('', 400);
50+
expect(error instanceof Error).to.be.true;
51+
});
52+
53+
it('Should be serializable', () => {
54+
const message = 'Some Error';
55+
const error = new HttpException(message, 400);
56+
expect(`${error}`).to.be.eql(`Error: ${message}`);
57+
});
58+
59+
it('Should serialize objects', () => {
60+
const obj = { foo: 'bar' };
61+
const error = new HttpException(obj, 400);
62+
expect(`${error}`).to.be.eql(`Error: ${JSON.stringify(obj)}`);
63+
expect(`${error}`.includes('[object Object]')).to.not.be.true;
64+
});
65+
66+
it('Should serialize sub errors', () => {
67+
const error = new NotFoundException();
68+
expect(`${error}`.includes('Not Found')).to.be.true;
69+
});
4770
});

0 commit comments

Comments
 (0)