import { Request , Response } from 'express' ; import { notify } from 'node-notifier' ; import { Logger } from '@services/logger.service' ; import { ErrorFactory } from '@factories/error.factory' ; import { IHTTPError , IRequest } from '@interfaces' ; dependency dependency see https class Catch { description private static instance : Catch ; private constructor ( ) { } description static get ( ) { if ( ! Catch . instance ) { Catch . instance = new Catch ( ) ; } return Catch . instance ; } description param err param req param res param next require require notification ( err , req , res , next ) { notify ( { title : `Error in ${ req . method } ${ req . url }` , message : err . name + '\n' + err . stack ? err . stack : err . message } ) ; next ( err , req , res , next ) ; } description param err param req param res param next factory ( err , req , res , next ) { next ( ErrorFactory . get ( err ) , req , res ) ; } description param err param req param res param next log ( err , req , res , next ) { const { user } = req as { user : { id : number ; } ; } ; if ( err . statusCode >= 500 ) { Logger . log ( 'error' , `${ req . headers [ 'x-forwarded-for' ] as string || req . connection . remoteAddress } HTTP/${ req . httpVersion } ${ err . statusCode } ${ req . method } ${ req . url } - ${ err . message } (#${ user ? user . id : 'unknown' }) : ${ err . stack ? '\n  ' + err . stack : '' } ${ req . body ? '\n  Payload :' + JSON . stringify ( req . body ) : '' }` ) ; } else { Logger . log ( 'error' , `${ req . headers [ 'x-forwarded-for' ] as string || req . connection . remoteAddress } HTTP/${ req . httpVersion } ${ err . statusCode } ${ req . method } ${ req . url } - ${ err . statusText } (#${ user ? user . id : 'unknown' }) : ${ err . errors . slice ( ) . shift ( ) } ${ req . body ? '\n  Payload :' + JSON . stringify ( req . body ) : '' }` ) ; } next ( err , req , res ) ; } description param err param req param res exit ( err , req , res , next ) { res . status ( err . statusCode ) ; res . json ( { statusCode : err . statusCode , statusText : err . statusText , errors : err . errors } ) ; } description param req param res notFound ( req , res ) { res . status ( 404 ) ; res . json ( { statusCode : 404 , statusText : 'Ooops... end point was not found' , errors : [ 'Looks like someone\'s gone mushroom picking\'' ] } ) ; } } const catcher = Catch . get ( ) ; export { catcher as Catch } ;