import { inject , injectable , Provider } from '@loopback/core' ; import { asMiddleware , ErrorWriterOptions , HttpErrors , LogError , Middleware , MiddlewareContext , Response , RestBindings , RestMiddlewareGroups , } from '@loopback/rest' ; @ injectable ( asMiddleware ( { group : 'validationError' , upstreamGroups : RestMiddlewareGroups . SEND_RESPONSE , downstreamGroups : RestMiddlewareGroups . CORS , } ) ) export class ValidationErrorMiddlewareProvider implements Provider < Middleware > { constructor ( @ inject ( RestBindings . SequenceActions . LOG_ERROR ) protected logError , @ inject ( RestBindings . ERROR_WRITER_OPTIONS , { optional : true } ) protected errorWriterOptions ? ) { } async value ( ) { const middleware = async ( ctx , next ) => { try { return await next ( ) ; } catch ( err ) { return this . handleError ( ctx , err ) ; } } ; return middleware ; } param context param err handleError ( context , err ) { if ( context . request . url === '/coffee-shops' ) { if ( err . statusCode === 422 && context . request . method === 'PATCH' ) { const customizedMessage = 'My customized validation error message' ; let customizedProps = { } ; if ( this . errorWriterOptions ?. debug ) { customizedProps = { stack : err . stack } ; } const errorData = { statusCode : 422 , message : customizedMessage , resolution : 'Contact your admin for troubleshooting.' , code : 'VALIDATION_FAILED' , ... customizedProps , } ; context . response . status ( 422 ) . send ( errorData ) ; this . logError ( err , err . statusCode , context . request ) ; return context . response ; } else { throw err ; } } } }