| 1 | import type { CommonResponse } from '../interfaces' |
| 2 | import { BadRequestException, HttpException } from '@nestjs/common' |
| 3 | import { AppException } from '../exceptions/app.exception' |
| 4 | |
| 5 | const MESSAGES = { |
| 6 | UNKNOWN_EXCEPTION_MESSAGE: 'Internal server error', |
| 7 | BAD_REQUEST_MESSAGE: 'Bad request', |
| 8 | } |
| 9 | |
| 10 | export function getExceptionPayload(exception: unknown, returnBadRequestDetails = false): Omit<CommonResponse<unknown>, 'url' | 'timestamp'> { |
| 11 | if (exception instanceof AppException) { |
| 12 | return getPayloadFromAppException(exception) |
| 13 | } |
| 14 | |
| 15 | if (exception instanceof BadRequestException) { |
| 16 | return getPayloadFromBadRequestException(exception, returnBadRequestDetails) |
| 17 | } |
| 18 | |
| 19 | if (exception instanceof HttpException) { |
| 20 | return getPayloadFromHttpException(exception) |
| 21 | } |
| 22 | |
| 23 | return getDefaultPayload() |
| 24 | } |
| 25 | |
| 26 | function getPayloadFromAppException(exception: AppException) { |
| 27 | const response = exception.getResponse() as CommonResponse<unknown> |
| 28 | |
| 29 | return { |
| 30 | data: response.data || {}, |
| 31 | code: response.code, |
| 32 | message: response.message, |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | function getPayloadFromHttpException(exception: HttpException) { |
| 37 | // eslint-disable-next-line ts/no-explicit-any |
| 38 | const response: any = exception.getResponse() |
| 39 | const code = exception.getStatus() |
| 40 | |
| 41 | const data = {} |
| 42 | |
| 43 | if (typeof response === 'string') { |
| 44 | return { |
| 45 | data, |
| 46 | code, |
| 47 | message: response, |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | return { |
| 52 | data: response.data ?? data, |
| 53 | code: response.code ?? code, |
| 54 | message: response.message ?? MESSAGES.UNKNOWN_EXCEPTION_MESSAGE, |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | function getPayloadFromBadRequestException(exception: BadRequestException, returnBadRequestDetails: boolean) { |
| 59 | if (returnBadRequestDetails) { |
| 60 | return getPayloadFromHttpException(exception) |
| 61 | } |
| 62 | |
| 63 | return { |
| 64 | data: {}, |
| 65 | code: 400, |
| 66 | message: MESSAGES.BAD_REQUEST_MESSAGE, |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | function getDefaultPayload() { |
| 71 | return { |
| 72 | data: {}, |
| 73 | code: 500, |
| 74 | message: MESSAGES.UNKNOWN_EXCEPTION_MESSAGE, |
| 75 | } |
| 76 | } |
| 77 |