javascript - 使用异步等待自动 try catch 路由器 Controller

标签 javascript node.js asynchronous

路由器:

  router.get('/available', VehicleController.getAvailable)

  router.put('/:vin/current-location', validate(vehicleValidation.currentLocation), VehicleController.saveCurrentLocation)

Controller

class VehicleController {
  async getAvailable (req, res, next) {
    try {
      res.json(await VehicleQueries.getAvailable())
    } catch (e) {
      next(e)
    }
  }

  async saveCurrentLocation (req, res, next) {
    try {
      res.json(await VehicleQueries.updateLocation(req.params.vin, req.body.lng, req.body.lat))
    } catch (e) {
      next(e)
    }
  }... etc etc

上面是一个使用新的异步和等待在 Nodejs 中构建的简单的 CRUD 应用程序。每个路由都会验证输入,然后传递到 Controller 。上面的示例调用另一个包含查询的类中的方法,该查询又返回一个 promise 。

正如你所看到的,我必须将每个 Controller 的代码包装在 try 和 catch 中。这变得相当令人恼火,我认为必须有一种更干净的方法。

是否可以以某种方式将 Controller 方法本身包装在 try catch 中?这样我就可以将 Controller 简化为:

class VehicleController {
  async getAvailable (req, res, next) {
      res.json(await VehicleQueries.getAvailable())
  }

  async saveCurrentLocation (req, res, next) {
      res.json(await VehicleQueries.updateLocation(req.params.vin, req.body.lng, req.body.lat))
  }... etc etc

最佳答案

您可以利用rest paremetersspread operator构建一个函数来处理 try/catch

async executeQuery(res,next,queryFunction,...queryArguments){
    try {
        res.json(await queryFunction(...queryArguments));
    } catch (e) {
        next(e);
    }
}
async getAvailable (req, res, next) {
    executeQuery(res,next,VehicleQueries.getAvailable);
}

async saveCurrentLocation (req, res, next) {
    executeQuery(res,next,VehicleQueries.updateLocation,req.params.vin, req.body.lng, req.body.lat);
}

关于javascript - 使用异步等待自动 try catch 路由器 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47016697/

相关文章:

java - 从java应用程序执行node.js脚本时出现问题

javascript - Knockout.js "visible"调用异步函数 - 不工作

javascript - 从数组中随机选择对象

javascript - 捕获 iframe 异常

node.js - 模型和迁移之间的重复数据

node.js - 连接到 nodejs https 服务器时连接重置

php - 使用 javascript/php 将 html 表单转换为 pdf 和电子邮件

JavaScript 评估问题(第 2 部分)

c# - 防止 WebBrowser 在导航时导致 UI 卡住?

c++ - 为现有异步代码创建 C++ 阻塞函数