[英]How do I use express middleware to act as an API responder?
My route definition is: 我的路线定义是:
app.put '/api/v1/user/oldest', userController.oldestAndUpdate, responder
in userController
, I have: 在
userController
,我有:
exports.oldestAndUpdate = (req, res, next) ->
doSomeStuff, (err, results) ->
return next err if err
req.apiResponse = results
next()
in my responder
, I have: 在我的
responder
,我有:
module.exports = (req, res, next) ->
response = req.apiResponse
response.status = 'ok'
res.json response
But how do I handle the error case? 但是我如何处理错误案例? If the
next(err)
is hit, how will my responder know there's an error? 如果
next(err)
被击中,我的响应者将如何知道有错误?
If there is ever an error passed to next
, the middleware chain and routing is stopped, and it skips straight to the error handling middleware. 如果传递给
next
一个错误,中间件链和路由将停止,并直接跳转到错误处理中间件。
The error handling middleware is special, as it has four arguments: err, req, res, next. 错误处理中间件是特殊的,因为它有四个参数:err,req,res,next。 Internally, express checks the arity (number of arguments) of every middleware handler, and if it has 4 it's used as the error handler.
在内部,express表示检查每个中间件处理程序的arity(参数数量),如果它有4则用作错误处理程序。 From here you can respond in the same style as the rest of your API.
在这里,您可以使用与其他API相同的样式进行响应。
There is an example error handler in the expressjs guide . expressjs指南中有一个示例错误处理程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.