From 9da2966acc5a6f9bd4b1d06dacb85d51037cf834 Mon Sep 17 00:00:00 2001 From: Brent Van Geertruy Date: Mon, 16 Apr 2018 16:42:21 +0200 Subject: [PATCH] Add support for generic errors with stacktrace and knexjs errors --- src/lib/errorParser.ts | 12 +++++++++++- src/lib/errors.ts | 2 +- tests/errorParser.test.ts | 21 +++++++++++++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/src/lib/errorParser.ts b/src/lib/errorParser.ts index 03fa67b..3384716 100644 --- a/src/lib/errorParser.ts +++ b/src/lib/errorParser.ts @@ -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 = error; + Object.assign(metaData, errorData); + } + } + // Express middleware validation errors if (error instanceof ev.ValidationError) { parsedError = new ValidationError(errors.INVALID_INPUT, { @@ -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, }; } diff --git a/src/lib/errors.ts b/src/lib/errors.ts index cfeff0f..7cb03c5 100644 --- a/src/lib/errors.ts +++ b/src/lib/errors.ts @@ -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; } } diff --git a/tests/errorParser.test.ts b/tests/errorParser.test.ts index 7274a64..02f09e4 100644 --- a/tests/errorParser.test.ts +++ b/tests/errorParser.test.ts @@ -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,