【问题标题】:Outsourcing try-catch-block from api-controllers into one single spot将 api-controller 的 try-catch-block 外包到一个地方
【发布时间】:2020-10-27 20:38:13
【问题描述】:

我的控制器中的每个动作都有相同的 try-catch-block:

  try {
    ...
  } catch (error) {
    return response.json({ message: error.message });
  }

我不想在每个控制器操作中重复它。

如何将 try-catch-block 放在一个位置,这样它就不会在整个项目中重复?

谢谢!

【问题讨论】:

    标签: javascript try-catch


    【解决方案1】:

    您可以使用这样的高阶函数来做到这一点:

    const handleError = func => (request, response, next) => {
      try {
        func(request, response, next)
      } catch (error) {
        return response.json({ message: error.message });
      }
    }
    

    然后你在你的路由中使用它和你的控制器这样:

    app.get("/whatever", handleError(myController))
    app.get("/anotherRoute", handleError(anotherController))
    

    您的控制器将仅包含您在示例中所拥有的 ...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-06
      • 2019-03-02
      • 2012-08-06
      • 1970-01-01
      • 1970-01-01
      • 2012-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多