import { Response } from 'express' ; import { ArgumentsHost , Catch , ExceptionFilter } from '@nestjs/common' ; import { BaseExceptionFilter } from '@nestjs/core' ; import { ApiContentType , ApiErrorMessage , ApiErrorParams , ApiHttpResponseCode , AppConfig , } from '@fc/app' ; import { ConfigService } from '@fc/config' ; import { LoggerLevelNames , LoggerService } from '@fc/logger' ; import { ExceptionsService } from '../exceptions.service' ; @ Catch ( ) export class UnhandledExceptionFilter extends BaseExceptionFilter implements ExceptionFilter { constructor ( protected readonly config , private readonly logger ) { super ( ) ; this . logger . setContext ( this . constructor . name ) ; } catch ( exception , host ) { this . logger . debug ( 'Exception from UnhandledException' ) ; const res = host . switchToHttp ( ) . getResponse ( ) ; const code = ExceptionsService . getExceptionCodeFor ( ) ; const id = ExceptionsService . generateErrorId ( ) ; const { name , message , stack } = exception ; const stackTrace = stack . split ( '\n' ) ; this . logger . error ( { type : name , code , id , message , stackTrace , } ) ; const httpErrorCode = ApiHttpResponseCode . ERROR_CODE_500 ; const errorMessage = { code , id , message } ; const exceptionParam = { res , error : errorMessage , httpResponseCode : httpErrorCode , } ; return this . errorOutput ( exceptionParam ) ; } private errorOutput ( errorParam ) { const { error , httpResponseCode , res } = errorParam ; const { apiOutputContentType } = this . config . get < AppConfig > ( 'App' ) ; this . logger . trace ( error , LoggerLevelNames . ERROR ) ; todo see https res . status ( httpResponseCode ) ; switch ( apiOutputContentType ) { case ApiContentType . HTML : this . getApiOutputHtml ( res , error ) ; break ; case ApiContentType . JSON : this . getApiOutputJson ( res , error ) ; break ; } } private getApiOutputHtml ( res , error ) { res . render ( 'error' , error ) ; } private getApiOutputJson ( res , error ) { res . json ( error ) ; } }