mirror of
https://github.com/nestjs/nest.git
synced 2026-02-21 23:11:44 +00:00
Make errors serializable by default
This commit is contained in:
@@ -30,4 +30,18 @@ export class HttpException extends Error {
|
||||
public getStatus(): number {
|
||||
return this.status;
|
||||
}
|
||||
|
||||
private getError(target) {
|
||||
if(typeof target === 'string') {
|
||||
return target;
|
||||
}
|
||||
|
||||
return JSON.stringify(target);
|
||||
}
|
||||
|
||||
public toString(): string {
|
||||
const message = this.getError(this.message);
|
||||
|
||||
return `Error: ${message}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,4 +44,27 @@ describe('HttpException', () => {
|
||||
statusCode: 404,
|
||||
});
|
||||
});
|
||||
|
||||
it('Should inherit from error', () => {
|
||||
const error = new HttpException('', 400);
|
||||
expect(error instanceof Error).to.be.true;
|
||||
});
|
||||
|
||||
it('Should be serializable', () => {
|
||||
const message = 'Some Error';
|
||||
const error = new HttpException(message, 400);
|
||||
expect(`${error}`).to.be.eql(`Error: ${message}`);
|
||||
});
|
||||
|
||||
it('Should serialize objects', () => {
|
||||
const obj = { foo: 'bar' };
|
||||
const error = new HttpException(obj, 400);
|
||||
expect(`${error}`).to.be.eql(`Error: ${JSON.stringify(obj)}`);
|
||||
expect(`${error}`.includes('[object Object]')).to.not.be.true;
|
||||
});
|
||||
|
||||
it('Should serialize sub errors', () => {
|
||||
const error = new NotFoundException();
|
||||
expect(`${error}`.includes('Not Found')).to.be.true;
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user