import { Catch, HttpException, ExceptionFilter, ArgumentsHost, Logger, HttpStatus as status } from '@nestjs/common'
import { HttpArgumentsHost } from '@nestjs/common/interfaces'
import { Response } from 'express'
import { OutgoingMessage } from 'http'
import validator from 'validator'
import { AxiosError, isAxiosError } from 'axios'
import { apiResponse } from '~/helpers/helper.api'
@Catch()
export class AppErrorException implements ExceptionFilter {
private readonly logger: Logger = new Logger('AppErrorException')
private statusCode: number = status.INTERNAL_SERVER_ERROR
private errMessage: string = 'Server is busy try again later!'
catch(exception: HttpException, host: ArgumentsHost): OutgoingMessage {
const args: HttpArgumentsHost = host.switchToHttp()
const res: Response = args.getResponse<Response>()
if (!isAxiosError(exception)) {
this.logger.error(`
==================================
======== Error Exception =========
==================================
name: ${exception.name}
code: ${exception.getStatus()}
message: ${exception.message}
response: ${JSON.stringify(exception.getResponse())}
Stack: ${exception.stack}
==================================
==================================
==================================
`)
this.statusCode = exception && !Number.isNaN(exception.getStatus()) ? exception.getStatus() : status.INTERNAL_SERVER_ERROR
const resMessage: any = exception.getResponse()
const customErrMessage = resMessage.hasOwnProperty('message') ? resMessage.message : resMessage
this.errMessage = exception && !validator.isEmpty(exception.message) ? customErrMessage : this.errMessage
} else {
const error: AxiosError = exception
this.logger.error(`
==================================
======== Error Exception =========
==================================
name: ${error.name}
code: ${error.status}
message: ${error.message}
response: ${JSON.stringify(error)}
Stack: ${error.stack}
==================================
==================================
==================================
`)
}
return res.status(this.statusCode).json(apiResponse({ stat_code: this.statusCode, err_message: this.errMessage }))
}
}