[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:
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:
We just need to wrap express router:
So the following middlewares can handle those error later.
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.
相关文章推荐
- webpack---粗暴解决Module build failed: Error: The node API for 'babel' has been moved to babel-core
- .NET-Demo for async and await
- R语言学习-问题解决-Error in output$nodeID : $ operator is invalid for atomic vectors
- node Promise (async/await)
- Compilation error in Node.getTextContent for jdk 6
- Node 7.6默认支持Async/Await
- node.js快速入门: learnyounode题目解答,http collect ,async/await in node...etc
- rosetta mpi error: protocols.jobdist.JobDistributors:(0)Master Node -- Waiting for job request:tag=1
- node 开发中常用的async/await 处理回调的几种形式
- node学习——Async+Await
- Node.js 7.0预计在9月30日发布,支持async/await,Koa 2.x也将随之发布
- Node.js Async Await in ES7
- node-使用promise, generator, async/await 读取文件的方法
- Nodejs Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'root'@'xx' (using password:YES)
- 利用async和await异步操作解决node.js里面fs模块异步读写,同步结果的问题
- org.apache.hadoop.hdfs.DFSClient: Error Recovery for null bad datanode[0] nodes == null问题可能出现的原因
- 从地狱到天堂,Node 回调向 async/await 转变
- async/await - 8.在for循环中正确的使用await
- 从不用 try-catch 实现的 async/await 语法说错误处理
- Mac使用mysql报Mac ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)错误