首页 > 解决方案 > 使用 try/catch on 方法

问题描述

我对许多对象方法使用多个相同的 try/catch 测试。所以,我想try/catch为我的代码创建方法,但不返回错误。

举个例子 :

  @autobind
  async forgottenPassword(req, res) {
    return this.callService(
      res,
      async () => await companyService.forgottenPassword(req.body.formData)
    );
  }

  callService(res, func) {
    try {
      func();
    } catch (error) {
      res.statusMessage = error.message;
      res.status(error.statusCode);
    } finally {
      res.end();
    }
  }

catch的从未被调用:/

有谁知道我做错了吗?

谢谢 !

标签: javascripttry-catchtry-catch-finally

解决方案


您需要进行 callServiceasyncawait在那里使用。

  @autobind
  async forgottenPassword(req, res) {
    return this.callService(
      res,
      async () => await companyService.forgottenPassword(req.body.formData)
    );
  }

  async callService(res, func) {
    try {
      await func();
    } catch (error) {
      res.statusMessage = error.message;
      res.status(error.statusCode);
    } finally {
      res.end();
    }
  }

推荐阅读