Make errors serializable by default

This commit is contained in:
Chris Sidell
2019-07-03 18:11:42 -07:00
parent acbeb1cd33
commit 724ddd8d23
2 changed files with 37 additions and 0 deletions

View File

@@ -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}`;
}
}

View File

@@ -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;
});
});