NodeJS 在catch块中抛出Error是否正确?

uinbv5nw  于 2023-02-08  发布在  Node.js
关注(0)|答案(1)|浏览(210)

我正在编写一个中间件,它有一个服务层和一个控制器层,为了向用户发送一个清晰的错误消息,我在服务层捕获任何错误,然后抛出一个新的Error,并带有一个个性化的消息,如下所示:

// services.js
  async getOneRecord(id) {
    const url = this.url + `/${id}`;
    return await axios.get(url).then((res) => res.data);
  }

// UserServices.js
    async getTaxValue(id) {
    try {
      const user = await this.getOneRecord(id);
      return Number(user.tax) / 100;
    } catch (error) {
      throw new Error(`User ID not found: ${id}`);
    }
  }

// UserController.js
  static async getUserTax(req, res) {
    const { userId } = req.params;

    try {
      const user = await userServices.getTaxValue(userId);
      return res.status(200).json(user);
    } catch (error) {
      return res.status(404).json(error.message);
    }
  }

我想知道这是否是正确的处理错误的方法,或者我是否做错了什么。

lztngnrs

lztngnrs1#

是的,它是正确的,并且与catch数据块中的throw新错误正常。
然而,忽略您捕获的error并不是一个好习惯。在getTaxValue中有很多事情可能出错,我认为其中大多数不应该导致“id not found”错误。因此,请非常明确地指出您预期的错误,使用条件测试它,然后重新抛出所有其他未更改的错误。还要设置.cause of errors
在您的情况下,可能是(来自用户记录端点的handling only 404 errors):

class NotFoundError extends Error {}

async getTaxValue(id) {
  try {
    const user = await this.getOneRecord(id);
    return Number(user.tax) / 100;
  } catch (error) {
    if (error.response && error.response.status == 404) { // see AxiosError
      throw new NotFoundError(`User ID not found: ${id}`, {cause: error});
    }
    throw error;
  }
}

// UserController.js
async function getUserTax(req, res) {
  const { userId } = req.params;
  try {
    const user = await userServices.getTaxValue(userId);
    return res.status(200).json(user);
  } catch (error) {
    return res.status(error instanceof NotFoundError ? 404 : 500).json(error.message);
  }
}

相关问题