| 1 | import { HttpException, HttpStatus } from '@nestjs/common' |
| 2 | import { getLocale } from '../interceptors/request-context.interceptor' |
| 3 | import { getCodeMessage } from '../utils' |
| 4 | |
| 5 | export class AppException extends HttpException { |
| 6 | readonly code: number |
| 7 | constructor(code: number) |
| 8 | constructor(code: number, message: string) |
| 9 | constructor(code: number, data: unknown) |
| 10 | constructor(code: number, message: string, data: unknown) |
| 11 | constructor(code: number, message?: string | object, data?: unknown) { |
| 12 | if (typeof message === 'object') { |
| 13 | if (data) { |
| 14 | throw new Error('invalid AppException') |
| 15 | } |
| 16 | |
| 17 | data = message |
| 18 | message = undefined |
| 19 | } |
| 20 | |
| 21 | if (message === undefined) { |
| 22 | const locale = getLocale() |
| 23 | message = getCodeMessage(code, data, locale) |
| 24 | } |
| 25 | |
| 26 | const payload = { |
| 27 | code, |
| 28 | message, |
| 29 | data, |
| 30 | } |
| 31 | |
| 32 | super( |
| 33 | HttpException.createBody(payload), |
| 34 | HttpStatus.BAD_REQUEST, |
| 35 | ) |
| 36 | this.code = code |
| 37 | } |
| 38 | } |
| 39 |