Skip to content

Commit

Permalink
feat: add custom status from args
Browse files Browse the repository at this point in the history
  • Loading branch information
horstenwillem committed Nov 2, 2023
1 parent 468f406 commit ff43f0c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
10 changes: 7 additions & 3 deletions src/lib/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,19 @@ export class ApiError<T = any> 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;
}
Expand Down
25 changes: 24 additions & 1 deletion tests/errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ describe('errors', () => {
},
},
stack: 'Something went wrong for...',
status: 503,
});
} catch (error) {
expect(error).toBeInstanceOf(Error);
Expand All @@ -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' } });
}
});
Expand All @@ -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',
Expand All @@ -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', () => {
Expand Down

0 comments on commit ff43f0c

Please sign in to comment.