gpt4 book ai didi

javascript - expressJS promise 和错误处理

转载 作者:行者123 更新时间:2023-12-03 07:41:57 24 4
gpt4 key购买 nike

我有一条路线,首先需要查询数据库,然后查询结果,查询另一个Web服务,然后查询结果呈现页面。
我已经解决了该流程,并试图找出错误处理方法。鉴于我与多种服务进行了交谈,因此我尝试在将错误退还给 express 人员之前先消除错误。

这是路线代码的结构:

Models.Episode.findById(request.params.episodeID)
.catch(function (error) {
throw (throwjs.notFound());
})
.then(function (episode) {
if (episode.getUser().id !== request.user.href) {
return next(throwjs.unauthorized("You do not have access to this podcast"));
}
return doSomeOtherAsyncStuff();
})
.then(function (queryResponse) {
renderPage();
})
.catch(function (error) {
next(error);
});

我的问题是第一次抓 fish 。我在此捕获中的目标是重新包装错误并停止执行并将错误发送给中间件。

使用上面的编写方式,执行停止,但是未调用我的快速错误处理程序。

我尝试将第一个渔获物重写为
.catch(function(error){
return next(error);
})

但这不能解决问题。我发现的唯一解决方案是将捕获移到最后。但是随后我丢失了故障位置的上下文。

关于我在做什么错的任何线索吗?
谢谢,olivier

最佳答案

我建议您采用其他方法,这样您就不必依赖长期运行的 promise 链。使用以下方法,您已将授权和验证分离到单独的中间件,因为它们不一定是实际情节处理程序本身所关心的。另外,这种表达方式更惯用。

另外一个好处是,您可以自由地将错误传递给错误处理程序,因此您可以进一步将错误与路由处理程序分离。

function validateEpisode(req, res, next) {
Models.Episode
.findById(req.params.episodeID)
.then(function(episode) {
req.yourApp.episode = episode;
next() // everything's good
})
.catch(function(error) {
// would be better to pass error in next
// so you can have a general error handler
// do something with the actual error
next(throwjs.notFound());
});
}

function authUserByEpisode(req, res, next) {
if (req.yourApp.episode.getUser().id !== req.user.href) {
next(throwjs.unauthorized("You do not have access to this podcast"));
}

next(); // authorized
}

function episodeController(req, res) {
// do something with req.yourApp.episode
}

app.get('/episode/:id', validateEpisode, authUserByEpisode, episodeController)

关于javascript - expressJS promise 和错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37750248/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com