Advertisement
aldikhan13

Nestjs global error handling

Feb 28th, 2025
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
TypeScript 5.79 KB | Source Code | 0 0
  1. import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus as status } from '@nestjs/common'
  2. import { HttpArgumentsHost } from '@nestjs/common/interfaces'
  3. import { Response } from 'express'
  4. import { OutgoingMessage } from 'node:http'
  5. import validator from 'validator'
  6.  
  7. import { Logger } from '~/infrastructure/common/helpers/logger.helper'
  8. import { ELoggerType } from '~/domain/enums/common.enum'
  9.  
  10. @Catch()
  11. export class AppErrorException implements ExceptionFilter {
  12.   private statCode: number = status.INTERNAL_SERVER_ERROR
  13.   private errCode: string = 'GENERAL_ERROR'
  14.   private errMessage: string = 'Application is busy please try again later!'
  15.  
  16.   private setLogError(name: string, type: ELoggerType, error: any): void {
  17.     if (error instanceof HttpException) {
  18.       const message: string = `
  19.           ==================================
  20.           ======== Error [HttpException] =========
  21.           ==================================
  22.  
  23.             name: ${error.name}
  24.             code: ${error.getStatus()}
  25.             message: ${error.message}
  26.             response: ${JSON.stringify(error.getResponse())}
  27.             stack: ${error.stack}
  28.  
  29.           ==================================
  30.           ==================================
  31.           ==================================
  32.           `
  33.  
  34.       Logger.log(name, type, message, error)
  35.       this.statCode = error && !Number.isNaN(error.getStatus()) ? error.getStatus() : status.INTERNAL_SERVER_ERROR
  36.  
  37.       const resMessage: any = error.getResponse()
  38.       const customErrMessage = resMessage.hasOwnProperty('message') ? resMessage.message : resMessage
  39.  
  40.       this.errMessage = error && !validator.isEmpty(error.message) ? customErrMessage : this.errMessage
  41.     } else if (error instanceof Error) {
  42.       const message: string = `
  43.           ==================================
  44.           ======== Exception [Error] =========
  45.           ==================================
  46.  
  47.             name: ${error.name}
  48.             message: ${error.message}
  49.             response: ${JSON.stringify(error)}
  50.             stack: ${error.stack}
  51.  
  52.           ==================================
  53.           ==================================
  54.           ==================================
  55.           `
  56.  
  57.       Logger.log(name, type, message, error)
  58.     } else {
  59.       const message: string = `
  60.       ==================================
  61.       ======== Exception [Common] =========
  62.       ==================================
  63.  
  64.         name: ${error.name}
  65.         message: ${error.message}
  66.         response: ${JSON.stringify(error)}
  67.         stack: ${error.stack}
  68.  
  69.       ==================================
  70.       ==================================
  71.       ==================================
  72.       `
  73.  
  74.       Logger.log(name, type, message, error)
  75.       this.statCode = error && error?.stat_code ? error.stat_code : this.statCode
  76.       this.errMessage = error && error?.error ? error.error : this.errMessage
  77.     }
  78.   }
  79.  
  80.   private setDefaultErrMsgAndErrCode(statCode: number): { err_code: string; error?: string } {
  81.     if (statCode === status.INTERNAL_SERVER_ERROR) {
  82.       this.errCode = 'GENERAL_ERROR'
  83.       this.errMessage = 'Application between service is busy please try again later!'
  84.     } else if (statCode === status.BAD_GATEWAY) {
  85.       this.errCode = 'SERVICE_ERROR'
  86.       this.errMessage = 'Application communication between server busy try again later!'
  87.     } else if (statCode === status.SERVICE_UNAVAILABLE) {
  88.       this.errCode = 'SERVICE_UNAVAILABLE'
  89.       this.errMessage = 'Application communication between server not available try again later!'
  90.     } else if (statCode === status.GATEWAY_TIMEOUT) {
  91.       this.errCode = 'SERVICE_TIMEOUT'
  92.       this.errMessage = 'Application communication between server timeout try again later!'
  93.     } else if (statCode === status.CONFLICT) {
  94.       this.errCode = 'DUPLICATE_RESOURCE'
  95.     } else if (statCode === status.UNPROCESSABLE_ENTITY) {
  96.       this.errCode = 'INVALID_REQUEST'
  97.     } else if (statCode === status.PRECONDITION_FAILED) {
  98.       this.errCode = 'REQUEST_COULD_NOT_BE_PROCESSED'
  99.     } else if (statCode === status.FORBIDDEN) {
  100.       this.errCode = 'ACCESS_DENIED'
  101.     } else if (statCode === status.UNAUTHORIZED) {
  102.       this.errCode = 'UNAUTHORIZED_TOKEN'
  103.     } else if (statCode === status.NOT_FOUND) {
  104.       this.errCode = 'UNKNOWN_RESOURCE'
  105.     }
  106.  
  107.     return { err_code: this.errCode, error: this.errMessage }
  108.   }
  109.  
  110.   catch(exception: HttpException, host: ArgumentsHost): OutgoingMessage {
  111.     const args: HttpArgumentsHost = host.switchToHttp()
  112.     const res: Response = args.getResponse<Response>()
  113.     const error: Record<string, any> = exception
  114.  
  115.     if (error instanceof HttpException) {
  116.       this.setLogError('ApplicationError', ELoggerType.ERROR, exception)
  117.       args.getNext()
  118.     } else if (error instanceof Error) {
  119.       this.setLogError('ApplicationError', ELoggerType.ERROR, error)
  120.       args.getNext()
  121.     } else {
  122.       this.setLogError('ApplicationError', ELoggerType.ERROR, error)
  123.       args.getNext()
  124.     }
  125.  
  126.     if (this.statCode === status.BAD_REQUEST) {
  127.       this.statCode = status.UNPROCESSABLE_ENTITY
  128.     } else if (this.statCode === status.FAILED_DEPENDENCY) {
  129.       this.statCode = status.INTERNAL_SERVER_ERROR
  130.     }
  131.  
  132.     const customErrorMsgAndErrCode: { err_code: string; error?: string } = this.setDefaultErrMsgAndErrCode(this.statCode)
  133.     if (customErrorMsgAndErrCode.err_code) {
  134.       this.errCode = customErrorMsgAndErrCode.err_code
  135.     } else if (customErrorMsgAndErrCode.err_code && customErrorMsgAndErrCode.error) {
  136.       this.errCode = customErrorMsgAndErrCode.err_code
  137.       this.errMessage = customErrorMsgAndErrCode.error
  138.     }
  139.  
  140.     return res.status(this.statCode).json({ stat_code: this.statCode, err_code: this.errCode, error: this.errMessage })
  141.   }
  142. }
  143.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement