首页 > 解决方案 > Node JS异步中间件未捕获异常

问题描述

我在 NodeJS 中有一个中间件异步函数。

module.exports = function (handler) {
return async (req, res, next) => {
try {
  console.log('async called...');
  await handler(req, res);
}
catch(ex) {
  console.log('catch...');
  next(ex);
  }
 };  
}

这是我的路线处理程序。

const asyncMiddleware = require('../middleware/async');

router.get('/', asyncMiddleware(async (req, res) => {
 await db.query('SELECT * xxx FROM aircraft LIMIT 10', 
function (err, rows, fields) {  
    if(err) throw err;
    res.send(rows)
 })
}));

问题是当我使用无效语法调用路由处理程序来模拟异常时,中间件的捕获没有从路由中的 throw err 捕获异常。

当我调用路由时,我会在控制台上调用异步...但没有捕获...。

有谁知道为什么会这样?

标签: node.js

解决方案


推荐阅读