javascript - 我怎样才能投入 .then 的承诺?
问题描述
我有以下js表达代码:
app.get('/lists2', (req, res) => {
mongo.getDB()
.then(db => db.collection('dogs'))
.then(collection => collection.find().toArray())
.then(array => res.json(success(array)))
// How can I throw in the middle of a promise to trigger express's middleware?
.catch(error => {
throw {message: "database error"};
});
});
app.use(function (err, req, res, next) {
const message = err.message || 'Encountered a server error';
const status = err.status || 500;
res.status(status).json({status, message});
})
我已经编写了一个中间件错误处理程序,所以我可以触发一个 API 错误响应,throw
问题是我不能扔进去,then
因为它在异步代码中,有什么方法可以解决这个问题吗?还是我的错误处理模式不正确?
解决方案
您应该使用next
(参见doc):
app.get('/lists2', (req, res, next) => {
mongo.getDB()
.then(db => db.collection('dogs'))
.then(collection => collection.find().toArray())
.then(array => res.json(success(array)))
// How can I throw in the middle of a promise to trigger express's middleware?
.catch(error => {
next(new Error("database error"));
});
});
app.use(function (err, req, res, next) {
const message = err.message || 'Encountered a server error';
const status = err.status || 500;
res.status(status).json({status, message});
})
推荐阅读
- macos-big-sur - 应用程序构建失败后如何长时间使用路径名删除应用程序文件 - Xcode 12 新构建系统与 MacOS 11.5.2
- i2c - I2C 从机欠载错误 TWI_THR 未按时填充
- r - str_wrap() 和 mutate() 在一个简单的自定义函数中传递给 ggplot()
- react-native - 如何在 Lottie 上渲染组件
- php - Woocommerce 向商品和购物车添加运输重量
- angular - 如何在 Overlay Angular 中显示内容?
- javascript - 使用 v 5.2.0 反应路由器问题(延迟更改路由)
- r - 如何从 Excel STOCKHISTORY 到 R 中的列表?
- android - 在 Android 上将 getString 与 JSONObject 类一起使用时获取 null
- android - 当我尝试运行它时,应用程序崩溃了。使用 Kotlin 中的 MVVM 和导航组件进行 Firebase 身份验证