Skip to content

Commit

Permalink
Add support for generic errors with stacktrace and knexjs errors
Browse files Browse the repository at this point in the history
  • Loading branch information
knor-el-snor committed Apr 16, 2018
1 parent 4d8963e commit 9da2966
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
12 changes: 11 additions & 1 deletion src/lib/errorParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,18 @@ import { errorConfig as errors } from './errorConfig';
import { errorDefaults } from './constants';

export function parseErrors(error: any) {
const metaData: any = {};
let parsedError = new ApiError(errorDefaults.DEFAULT_HTTP_CODE, errorDefaults.DEFAULT_ERROR); // Default error

// Other errors
if (error instanceof Error) {
Object.assign(metaData, { stack: JSON.stringify(error.stack) });
if (error.hasOwnProperty('schema') && error.hasOwnProperty('detail')) { // knex.js specific errors
const errorData = <any>error;
Object.assign(metaData, errorData);
}
}

// Express middleware validation errors
if (error instanceof ev.ValidationError) {
parsedError = new ValidationError(errors.INVALID_INPUT, {
Expand All @@ -25,6 +35,6 @@ export function parseErrors(error: any) {
code: parsedError.code,
title: parsedError.message,
detail: parsedError.detail || parsedError.message,
meta: error instanceof Error ? { stack: parsedError.stack } : undefined, // At least add stacktrace for unknown errors
meta: Object.keys(metaData).length !== 0 ? metaData : undefined,
};
}
2 changes: 1 addition & 1 deletion src/lib/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export class ApiError extends Error {
this.code = error.code;
this.status = status;
this.detail = detail;
if (stack) this.stack = JSON.stringify(stack);
if (stack) this.stack = stack;
}
}

Expand Down
21 changes: 21 additions & 0 deletions tests/errorParser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,27 @@ describe('errorParser', () => {
// TODO: Other custom errors extending from Error
});


describe('Knex.js errors', () => {
const error = new Error('Some error...');
Object.assign(error, { stack: 'myStack', detail: 'some details', schema: 'public' });

const parsedError = parseErrors(error);
expect(parsedError).toMatchObject({
id: expect.any(String),
status: defaultError.status,
code: defaultError.code,
title: defaultError.message,
detail: defaultError.message,
meta: {
stack: JSON.stringify('myStack'),
detail: 'some details',
schema: 'public',
},
});

});

describe('Express Validation errors', () => {
const options = {
flatten: false,
Expand Down

0 comments on commit 9da2966

Please sign in to comment.