如何在express.js中捕获`.param`回调错误?

时间:2014-12-11 15:02:54

标签: node.js express

在我的应用程序中,我想验证某些路径的某些参数。然后,如果它无效,我想从next(err)捕获错误并将其转换为某种协议格式。看一下代码:

app = express();

router = express.Router();

router.param("id", function(req, res, next, id) {
  // something went wrong and we are:
  next(new Error("Bad ID"));
});

router.get("/some/route/to/:id", function(...) {...});

router.use(function(error, req, res, next) {
  // here I want to get the "Bad ID" error,
  // but instead, this middleware is not invoked
});

app.use(router);

app.use(function(err, req, res, next) {
  // and this middleware finally catches "Bad ID" error..
});

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

没有尝试运行它,但它看起来是正确的......

请尝试以下操作:app.param代替router.paramrouter.use(error middleware)代替app.use(...)