Skip to content

Commit bcbdac2

Browse files
authored
Merge pull request #392 from Quickchive/feat/change-global-exception-response-interface
feat: 전역 에러 처리 응답 인터페이스 수정
2 parents 8ff567a + 4832eee commit bcbdac2

File tree

1 file changed

+49
-14
lines changed

1 file changed

+49
-14
lines changed

src/common/exceptions/http-exception.filter.ts

Lines changed: 49 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,32 +7,67 @@ import {
77
import { Request, Response } from 'express';
88
import { logger } from '../logger';
99

10-
@Catch(HttpException)
10+
class ErrorResponse {
11+
statusCode: number;
12+
path: string;
13+
message: string;
14+
data?: any;
15+
16+
constructor({
17+
statusCode,
18+
path,
19+
message,
20+
data,
21+
}: {
22+
statusCode: number;
23+
path: string;
24+
message: string;
25+
data?: any;
26+
}) {
27+
this.statusCode = statusCode;
28+
this.path = path;
29+
this.message = message;
30+
this.data = data;
31+
}
32+
}
33+
34+
@Catch()
1135
export class HttpExceptionFilter implements ExceptionFilter {
1236
catch(exception: HttpException, host: ArgumentsHost) {
1337
const ctx = host.switchToHttp();
1438
const response = ctx.getResponse<Response>();
1539
const request = ctx.getRequest<Request>();
1640
const status = exception.getStatus();
17-
const error = exception.getResponse() as {
18-
error: string;
19-
statusCode: number;
20-
message: string | string[];
21-
};
2241
const { ip, method, url } = request;
2342
logger.error(
2443
`${method} - ${url} - ${ip.split(':').at(-1)} - ${JSON.stringify(
2544
exception,
2645
)}`,
2746
);
2847

29-
typeof error === 'string'
30-
? response.status(status).json({
31-
statusCode: status,
32-
message: error,
33-
})
34-
: response.status(status).json({
35-
...error,
36-
});
48+
const exceptionResponse = exception.getResponse() as {
49+
error: string;
50+
message?: string | string[];
51+
data?: any;
52+
};
53+
const exceptionMessage = (() => {
54+
if (
55+
exceptionResponse?.message &&
56+
Array.isArray(exceptionResponse.message)
57+
) {
58+
return exceptionResponse.message.join(' ');
59+
}
60+
61+
return exception.message;
62+
})();
63+
64+
response.status(status).json(
65+
new ErrorResponse({
66+
statusCode: status,
67+
path: request.url,
68+
message: exceptionMessage,
69+
data: exceptionResponse?.data,
70+
}),
71+
);
3772
}
3873
}

0 commit comments

Comments
 (0)