import { Provide } from '@midwayjs/decorator' ; import { IWebMiddleware , IMidwayWebNext , MidwayWebMiddleware , } from '@midwayjs/web' ; import { Context } from '@/interface' ; import MyError from '../util/my-error' ; @ Provide ( ) export class ErrorHandlerMiddleware implements IWebMiddleware { resolve ( ) { return errHandleMiddleware ; } } async function errHandleMiddleware ( ctx , next ) { try { await next ( ) ; if ( ctx . status === 404 ) { ctx . body = { code : 404 , message : 'Not Found' } ; } } catch ( err ) { ctx . app . emit ( 'error' , err , ctx ) ; const myerr = err as MyError ; const [ message , messageStatus ] = myerr . message ?. split ( ' &>' ) ; let status = myerr . status || parseInt ( messageStatus ) || 500 ; if ( myerr . name === 'ValidationError' || message === 'ValidationError' ) { status = 422 ; } ctx . _internalError = myerr ; const error = status === 500 && ctx . app . config . env === 'prod' ? 'Internal Server Error' : message ; ctx . body = { code : status , message : error } ; if ( status === 422 ) { ctx . body . data = myerr . errors || myerr . details ; } ctx . status = status ; } }