import * as express from 'express' ; import { ExpressErrorMiddlewareInterface , HttpError , Middleware } from 'routing-controllers' ; import { ValidationError } from 'class-validator' ; import { Logger , LoggerInterface } from '../../decorators/Logger' ; import { env } from '../../env' ; @ Middleware ( { type : 'after' } ) export class ErrorHandlerMiddleware implements ExpressErrorMiddlewareInterface { public isProduction = env . isProduction ; constructor ( @ Logger ( __filename ) private log ) { } param { any } error param { express . Request } req param { express . Response } res param { express . NextFunction } next public error ( error , _req , res , _next ) { const responseObject = { } as any ; if ( error && Array . isArray ( error . errors ) && error . errors . every ( ( element ) => element instanceof ValidationError ) ) { res . status ( 422 ) ; console . log ( 'Inside' ) ; responseObject . message = "You have an error in your request's body. Check 'errors' field for more details!" ; responseObject . status = 0 ; responseObject . data = { } ; responseObject . data . message = [ ] ; error . errors . forEach ( ( element ) => { Object . keys ( element . constraints ) . forEach ( ( type ) => { responseObject . data . message . push ( `property ${ element . constraints [ type ] }` ) ; } ) ; } ) ; } else { if ( error instanceof HttpError && error . httpCode ) { res . status ( error . httpCode ) ; } else { res . status ( 500 ) ; } if ( error instanceof Error ) { const developmentMode = ! this . isProduction ; if ( error . name && ( developmentMode || error . message ) ) { responseObject . name = error . name ; } switch ( error . name ) { case 'AuthorizationRequiredError' : responseObject . message = 'Unauthorized' ; break ; default : responseObject . message = error . message ; break ; } if ( error . stack && developmentMode ) { responseObject . stack = error . stack ; } } else if ( typeof error === 'string' ) { responseObject . message = error ; } } if ( this . isProduction ) { this . log . error ( error . name , error . message ) ; } else { this . log . error ( error . name , error . stack ) ; } res . json ( responseObject ) ; } }