import serializeError = require ( 'serialize-error' ) ; import { RestError , InvalidJsonError , InternalError , ValidationFailureError } from '../errors' ; import { Logger , LoggerFactory } from '../../logging' ; export class RestErrorMiddleware { public static readonly LOGGER : Logger = LoggerFactory . getLogger ( ) ; static normalizeToRestError ( err , req , res , next ) { if ( err instanceof RestError ) { return next ( err ) ; } if ( err instanceof SyntaxError ) { return next ( new InvalidJsonError ( ) ) ; } return next ( new InternalError ( err ) ) ; } static serializeRestError ( err , req , res , next ) { if ( err instanceof InternalError ) { const logFriendlyErrorMessage = serializeError ( err . originalError ) ; RestErrorMiddleware . LOGGER . error ( logFriendlyErrorMessage ) ; } else { const logFriendlyErrorMessage = serializeError ( err ) ; RestErrorMiddleware . LOGGER . warn ( logFriendlyErrorMessage ) ; } return res . status ( err . httpStatusCode ) . json ( { error : err } ) ; } }