[Node] Catch error for async await
Posted Answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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的主要内容,如果未能解决你的问题,请参考以下文章
Whitelabel Error PageThis application has no explicit mapping for /error, so you are seeing this as
错误:TypeError:尝试为网站 node.js 注册用户时无法读取未定义的属性“catch”
The eventual following stack trace is caused by an error thrown for debugging purposes as well as to
This application has no explicit mapping for /error, so you are seeing this as a fallback.
报This application has no explicit mapping for /error, so you are seeing this as a fallback解决方法
报This application has no explicit mapping for /error, so you are seeing this as a fallback解决方法