码迷,mamicode.com
首页 > 其他好文 > 详细

[Node] Catch error for async await

时间:2017-06-20 00:23:31      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:efi   blog   save   style   ati   dir   express   mongod   pre   

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

标签:efi   blog   save   style   ati   dir   express   mongod   pre   

原文地址:http://www.cnblogs.com/Answer1215/p/7051172.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!