diff --git a/src/lib/errors.ts b/src/lib/errors.ts index 09baa8d..c818d25 100644 --- a/src/lib/errors.ts +++ b/src/lib/errors.ts @@ -11,15 +11,19 @@ export class ApiError extends Error { detail?: T; isApiError: boolean; - constructor(status: number, error: ErrorType, args: { message?: string; detail?: T; stack?: any } = {}) { - const { message, detail, stack } = args; + constructor( + status: number, + error: ErrorType, + args: { message?: string; detail?: T; stack?: any; status?: number } = {}, + ) { + const { message, detail, stack, status: customStatus } = args; super(message || error.message); this.name = 'ApiError'; this.isApiError = true; this.id = uuid.v1(); this.code = error.code; this.i18n = error.i18n; - this.status = status; + this.status = customStatus || status; this.detail = detail; if (stack) this.stack = stack; } diff --git a/tests/errors.test.ts b/tests/errors.test.ts index e980b8d..787df7d 100644 --- a/tests/errors.test.ts +++ b/tests/errors.test.ts @@ -38,6 +38,7 @@ describe('errors', () => { }, }, stack: 'Something went wrong for...', + status: 503, }); } catch (error) { expect(error).toBeInstanceOf(Error); @@ -46,6 +47,7 @@ describe('errors', () => { expect(error.id).toEqual(expect.any(String)); expect(error.toString()).toEqual('ApiError: Error with a custom message'); expect(error.stack).not.toBeNull(); + expect(error.status).toEqual(503); expect(error.detail).toEqual({ badFormatFields: { name: 'email' } }); } }); @@ -66,7 +68,7 @@ describe('errors', () => { } }); - it('Should throw an InternalServerError with custom error', () => { + it('Should throw an GenericError with custom error', () => { const args = { code: 'CUSTOM_CODE', message: 'Error with a custom message', @@ -85,6 +87,27 @@ describe('errors', () => { expect(error.detail).toBeUndefined(); } }); + + it('Should throw an GenericError with custom status', () => { + const args = { + code: 'CUSTOM_CODE', + message: 'Error with a custom message with custom status', + }; + + try { + throw new GenericError(args, { status: 503 }); + } catch (error) { + expect(error).toBeInstanceOf(Error); + expect(error).toBeInstanceOf(GenericError); + expect(error.name).toEqual('GenericError'); + expect(error.code).toEqual(args.code); + expect(error.id).toEqual(expect.any(String)); + expect(error.toString()).toEqual('GenericError: Error with a custom message with custom status'); + expect(error.stack).not.toBeNull(); + expect(error.detail).toBeUndefined(); + expect(error.status).toEqual(503); + } + }); }); describe('BadRequestError', () => {