import { Provide } from '@midwayjs/decorator' ; import { IWebMiddleware , MidwayWebMiddleware , IMidwayWebNext , } from '@midwayjs/web' ; import { Context } from 'egg' ; import { res } from '../common/utils' ; import { ValidationError } from 'joi' ; @ Provide ( ) export class ExecptionMiddleware implements IWebMiddleware { resolve ( ) { return async ( ctx , next ) => { try { await next ( ) ; } catch ( err ) { ctx . logger . error ( `[Exception] ${ err }` ) ; ctx . set ( 'Content-Type' , 'application/json' ) ; const status = ( err instanceof ValidationError ? 422 : err . status ) || 500 ; const message = status === 500 && ctx . app . config . env === 'prod' ? '服务器好像出了点问题...稍后再试试' : err . message ; ctx . status = status ; ctx . body = res ( { message , code : status } ) ; } } ; } }