adonis异常处理

来源:互联网 发布:浩鹏加密软件 编辑:程序博客网 时间:2024/06/06 13:43
adonis框架对请求生命周期中抛出的各种异常提供了处理方法以及用户自定义异常处理器的方式,有关的类为:Ignitor->_setupExceptionsHandler():点火器类,在启动程序时查找处理器类Server->_getExceptionHandler():服务器类查找对应异常的处理器方法Server->_handleException():处理异常的方法Server->handle():处理请求方法,在最后的Promise对象上注册了处理异常的方法Exception:通过供应商注册的类似异常管理类Ignitor->_setupExceptionsHandler():/*_setupExceptionsHandler () {//获取用户自定义异常处理器文件相对目录    const handleRelativePath = `${DIRECTORIES['exceptions']}/Handler`    try {//请求用户自定义的异常处理器      require(path.join(this._appRoot, 'app', handleRelativePath))      debug('using %s for handling exceptions', `${this.appNamespace}/${handleRelativePath}`)//使用已注册的异常管理器将通配符异常绑定到用户自定义的异常处理器      this._fold.ioc.use('Adonis/Src/Exception').bind('*', `${this.appNamespace}/${handleRelativePath}`)    } catch (error) {      console.log(error)      if (error.code !== 'MODULE_NOT_FOUND') {        throw error      }      debug('using %s for handling exceptions', '@provider:Adonis/Exceptions/Handler')//如果没有用户自定义的异常处理器,那么采用框架自带的异常处理器      this._fold.ioc.use('Adonis/Src/Exception').bind('*', '@provider:Adonis/Exceptions/Handler')    }  }*/Server->handle()/*handle (req, res) {    const ctx = new this.Context(req, res)    const response = ctx.response    const request = ctx.request    this      ._composeServerMiddleware(ctx)()      .then(() => {        if (!response.isPending) {          debug('step:1.2 server level middleware ended the response explicitly by calling end')          return        }        if ((response.lazyBody.content || response.response.statusCode === 204) && response.lazyBody.method) {          debug('step:1.2 server level middleware ended the response')          response.end()          return        }        const route = this.Route.match(request.url(), request.method(), request.hostname())        if (!route) {          throw new GE.HttpException(`Route not found ${request.url()}`, 404)        }        ctx.params = route.params        ctx.subdomains = route.subdomains        request.params = route.params        debug('step:2 route found for %s url', request.url())        const finalHandler = this._wrapRouteHandler(route.route._handler)        return this._composeRequestMiddleware(route.route._middleware, finalHandler, ctx)()      })      .then(() => {        debug('ending response for %s url', request.url())        this._endResponse(response)      })//在最后的Promise对象上注册了异常处理方法      .catch((error) => {        console.log('请求生命周期发生了异常:'+error)        debug('received error on %s url', request.url())        this._handleException(error, ctx)      })  }Server->_handleException()/*_handleException (error, ctx) {//默认的错误消息    error.message = error.message || 'Internal server error'//默认的错误码    error.status = error.status || 500//处理器函数    const exceptionHandler = this._getExceptionHandler(error)    const exceptionReporter = this._getExceptionReporter(error)    exceptionReporter(error, { request: ctx.request, auth: ctx.auth })    Promise//调用处理器函数      .resolve(exceptionHandler(error, ctx))      .then(() => {//结束响应        this._endResponse(ctx.response)      })//这个过程发生异常的处理方式,这是最后防线      .catch((hardError) => {        // was not expecting this at all        ctx.response.status(500).send(hardError)        ctx.response.end()      })  }*/Server->_getExceptionHandler()/*_getExceptionHandler (error) {//采用忽略通配符处理器的方式从异常管理器中查找相应的处理器    const handler = this.Exception.getHandler(error.name, true)    if (handler) {//找到直接返回      return handler    }    if (error.handle) {//如果异常自带处理器,则调用自带处理器      return function (...args) { return error.handle(...args) }    }//最次用通配符处理器    return this.Exception.getWildcardHandler() || function (err, { response }) {      response.status(error.status).send(`${err.name}: ${err.message}\n${err.stack}`)    }  }//使用处理器的顺序是:特别为异常在管理器中注册的处理器->异常自带的处理器->用户自定义的通配符异常处理器类->框架自带的通配符异常处理器*/*/