希望这是一个简单的,但我有一些自定义中间件,我想将 404 或 401 等返回给用户并停止传播其他处理程序等。
我原以为我可以做类似的事情:
function SomeMiddleware(req, res, next) {
if(user.notRealOrSomething)
{ throw new HttpException(401, "Tough luck buddy"); }
return next();
}
但是找不到任何关于如何最好地做到这一点的具体信息。
最佳答案
您假设将错误传递给 next()
函数。
function SomeMiddleware(req, res, next) {
if(user.notRealOrSomething) {
return next(throw new HttpException(401, "Tough luck buddy"));
}
next();
}
您传递给 next
的任何参数都将被视为错误,但 'route'
除外,它会跳到下一个路由。
当 next 被错误调用时,错误中间件将被执行。
function (err, req, res, next) {
// err === your HttpException
}
Express.js 会将任何带有 4 个参数的中间件视为错误中间件。
Error-handling middleware are defined just like regular middleware, however must be defined with an arity of 4, that is the signature (err, req, res, next):
所有这些都很好地记录在:http://expressjs.com/guide/error-handling.html
关于javascript - 从具有特定 http 状态的 express 中间件退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18017430/