如何在express.js中抛出404错误?

时间:2016-04-25 10:06:57

标签: javascript node.js express

在app.js中,我有

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

因此,如果我请求某些不存在的网址http://localhost/notfound,则会执行以上代码。

在像http://localhost/posts/:postId这样的现有网址中,我想在访问一些不存在postId或删除postId时抛出404错误。

Posts.findOne({_id: req.params.id, deleted: false}).exec()
  .then(function(post) {
    if(!post) {
      // How to throw a 404 error, so code can jump to above 404 catch?
    }

4 个答案:

答案 0 :(得分:3)

In Express, a 404 isn't classed as an 'error', so to speak - 这背后的原因是404通常不是一个出错的迹象,只是服务器找不到任何东西。最好的办法是在路由处理程序中明确发送404:

Posts.findOne({_id: req.params.id, deleted: false}).exec()
  .then(function(post) {
    if(!post) {
      res.status(404).send("Not found.");
    }

或者,如果感觉重复代码过多,您可以随时将该代码拉入函数中:

function notFound(res) {
    res.status(404).send("Not found.");
}

Posts.findOne({_id: req.params.id, deleted: false}).exec()
      .then(function(post) {
        if(!post) {
          notFound(res);
        }

我不建议在这种情况下使用中间件仅仅因为我觉得它使代码不太清楚 - 404是数据库代码找不到任何东西的直接结果,所以在路由处理程序。

答案 1 :(得分:3)

我有相同的app.js结构,我在路由处理程序中以这种方式解决了这个问题:

router.get('/something/:postId', function(req, res, next){
    // ...
    if (!post){
        next();
        return;
    }
    res.send('Post exists!');  // display post somehow
});

next()函数将调用下一个中间件,即如果它位于app.js中的路由之后,它就是error404处理程序。

答案 2 :(得分:0)

答案 3 :(得分:0)

您可以使用此路由器和路由器的末端。

app.use('/', my_router);
....
app.use('/', my_router);

app.use(function(req, res, next) {
        res.status(404).render('error/404.html');
    });