首页 > 代码库 > [Node] Catch error for async await
[Node] Catch error for async await
When we try to do MongoDB opration, mongoose return Promise, we can use async/await to simply the code:
const mongoose = require(‘mongoose‘);const Store = mongoose.model(‘Store‘);exports.createStore = async (req, res) => { const store = new Store(req.body); await store.save(); res.redirect(‘/‘);};
The problme here is no error handling, we can use try catch, there is another approach is function composion.
We can define a high order function:
exports.catchErrors = (fn) => { return function(req, res, next) { return fn(req, res, next).catch(next); };};
We just need to wrap express router:
router.post(‘/add‘, catchErrors(storeCtrl.createStore));
So the following middlewares can handle those error later.
[Node] Catch error for async await
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。