您的位置:首页 > Web前端 > Node.js

[Node] Catch error for async await

2017-06-19 23:34 197 查看
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: