如何使用快速中间件作为API响应器



我的路由定义是:

app.put '/api/v1/user/oldest', userController.oldestAndUpdate, responder

userController中,我有:

exports.oldestAndUpdate = (req, res, next) ->
  doSomeStuff, (err, results) ->
    return next err if err
    req.apiResponse = results
    next()

在我的responder中,我有:

module.exports = (req, res, next) ->
  response = req.apiResponse
  response.status = 'ok'
  res.json response

但是我如何处理错误情况呢?如果next(err)被击中,我的响应者如何知道有一个错误?

如果有错误传递给next,中间件链和路由将停止,并直接跳转到错误处理中间件。

错误处理中间件是特殊的,因为它有四个参数:err, req, res, next。在内部,express检查每个中间件处理程序的数量(参数数量),如果它有4个,它就被用作错误处理程序。从这里开始,您可以使用与API其余部分相同的样式进行响应。

在expressjs指南中有一个示例错误处理程序

最新更新