import Context from "../Context" ; import MiddlewareError from "../errors/MiddlewareError" ; import IRequest from "../IRequest" ; import IResponse from "../IResponse" ; import { NextFunction } from "../MiddlewareFactory" ; import ILogger from "../utils/ILogger" ; export param { Context } context param { ( MiddlewareError | Error ) } err param { Request } req param { Response } res param { NextFunction } next param { ILogger } logger returns { void } export default function errorMiddleware ( context , err , req , res , next , logger ) { if ( res . headersSent ( ) ) { logger . warn ( `Error middleware received an error, but response.headersSent is true, pass error to next middleware` , context . contextId ) ; return next ( err ) ; } if ( err instanceof MiddlewareError ) { logger . error ( `ErrorMiddleware: Received a MiddlewareError, fill error information to HTTP response` , context . contextId ) ; logger . error ( `ErrorMiddleware: ErrorName=${ err . name } ErrorMessage=${ err . message }  ErrorHTTPStatusCode=${ err . statusCode } ErrorHTTPStatusMessage=${ err . statusMessage } ErrorHTTPHeaders=${ JSON . stringify ( err . headers ) } ErrorHTTPBody=${ JSON . stringify ( err . body ) } ErrorStack=${ JSON . stringify ( err . stack ) }` , context . contextId ) ; logger . error ( `ErrorMiddleware: Set HTTP code: ${ err . statusCode }` , context . contextId ) ; res . setStatusCode ( err . statusCode ) ; if ( err . statusMessage ) { logger . error ( `ErrorMiddleware: Set HTTP status message: ${ err . statusMessage }` , context . contextId ) ; res . setStatusMessage ( err . statusMessage ) ; } if ( err . headers ) { for ( const key in err . headers ) { if ( err . headers . hasOwnProperty ( key ) ) { const value = err . headers [ key ] ; if ( value ) { logger . error ( `ErrorMiddleware: Set HTTP Header: ${ key }=${ value }` , context . contextId ) ; res . setHeader ( key , value ) ; } } } } if ( err . contentType && req . getMethod ( ) !== "HEAD" ) { logger . error ( `ErrorMiddleware: Set content type: ${ err . contentType }` , context . contextId ) ; res . setContentType ( err . contentType ) ; } logger . error ( `ErrorMiddleware: Set HTTP body: ${ JSON . stringify ( err . body ) }` , context . contextId ) ; if ( err . body && req . getMethod ( ) !== "HEAD" ) { res . getBodyStream ( ) . write ( err . body ) ; } } else if ( err instanceof Error ) { logger . error ( `ErrorMiddleware: Received an error, fill error information to HTTP response` , context . contextId ) ; logger . error ( `ErrorMiddleware: ErrorName=${ err . name } ErrorMessage=${ err . message } ErrorStack=${ JSON . stringify ( err . stack ) }` , context . contextId ) ; logger . error ( `ErrorMiddleware: Set HTTP code: ${ 500 }` , context . contextId ) ; res . setStatusCode ( 500 ) ; } else { logger . warn ( `ErrorMiddleware: Received unhandled error object` , context . contextId ) ; } next ( ) ; }