Skip to content

Commit

Permalink
feat: add logs for HTTP 4xx, 5xx error
Browse files Browse the repository at this point in the history
  • Loading branch information
skgndi12 committed Nov 7, 2023
1 parent 1f84dde commit 240fdf2
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
19 changes: 18 additions & 1 deletion api/src/controller/http/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import 'express-async-errors';
import { HttpError as ValidationError } from 'express-openapi-validator/dist/framework/types';
import { Logger } from 'winston';

import { getErrorMessage } from '@src/util/error';

import {
BadRequestErrorType,
CustomError,
Expand Down Expand Up @@ -56,7 +58,7 @@ export class Middleware {
} else {
customError = new CustomError(
InternalErrorType.UNEXPECTED,
'Unexpected error happened'
`Unexpected error occured, error: ${getErrorMessage(err)}`
);
}

Expand Down Expand Up @@ -129,6 +131,21 @@ export class Middleware {
) => {
const statusCode = this.getStatusCode(err);

switch (true) {
case statusCode >= 500:
this.logger.error('5xx error occured', {
error: err,
statusCode: statusCode
});
break;
case statusCode >= 400:
this.logger.warn('4xx error occured', {
error: err,
statusCode: statusCode
});
break;
}

res.locals.error = err;
res.status(statusCode);
res.send({
Expand Down
6 changes: 3 additions & 3 deletions api/test/controller/http/middleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ describe('Test middleware', () => {
let baseUrl: string;

beforeAll(async () => {
mockLogger = {};
mockLogger = { error: jest.fn(), warn: jest.fn() };
testHttpServer = new TestHttpServer(mockLogger as Logger);
baseUrl = '/api/v1/dev';
await testHttpServer.start();
Expand Down Expand Up @@ -215,7 +215,7 @@ describe('Test middleware', () => {
expect(response.status).toEqual(500);
expect(response.body).toStrictEqual({
type: InternalErrorType.UNEXPECTED,
messages: ['Unexpected error happened']
messages: ['Unexpected error occured, error: Error from throwSyncError']
});
});

Expand All @@ -226,7 +226,7 @@ describe('Test middleware', () => {
expect(response.status).toEqual(500);
expect(response.body).toStrictEqual({
type: InternalErrorType.UNEXPECTED,
messages: ['Unexpected error happened']
messages: ['Unexpected error occured, error: Error from throwAsyncError']
});
});

Expand Down

0 comments on commit 240fdf2

Please sign in to comment.