【问题标题】:Make error inside `try` not handled by `catch`在 `catch` 未处理的`try` 中出错
【发布时间】:2022-01-25 07:40:45
【问题描述】:

我希望try 块内抛出的特定错误不由catch(err) 处理

例子:

const someFunc = async () => {
  ...
  try {
    ...
    // This error should not be handled by the catch and go straight to the middleware
    throw {
      status: 404,
      message: "Not Found",
    };
  } catch (error) {
    throw {
      status: 500,
      message: "Something went wrong",
      reason: error,
    };
  }
};

然后中间件处理错误。

export const errorHandler: ErrorRequestHandler = (err, req, res, next) => {
  const { status = 500, message, reason } = err;
  res.status(status).json({
    success: false,
    message: message || "Something went wrong",
    reason: reason || undefined,
  });
};

【问题讨论】:

  • 不太可能,我不认为。您可以创建一个自定义错误函数,将错误传递给您的中间件,但您不能直接在 try catch 块中抛出而不被捕获。
  • 您可以实现多个 catch 块来处理不同类型的错误。见:Conditional catch-blocks
  • 没有什么要求你抛出Error的实例,但你应该在你的代码中。请参阅有关错误处理的快速文档:expressjs.com/en/guide/error-handling.html

标签: javascript typescript express error-handling


【解决方案1】:

如果您在 try-block 内抛出错误,catch 将捕获它。如果您不想捕获的错误被抛出,您最好检查catch-block,如果是,请重新抛出它。

const someFunc = async () => {
  try {
    throw {
      status: 404,
      message: "Not Found",
    };
  } catch (error) {
    // If a 404 error is caught, rethrow it.
    if (error.status === 404) {
      throw error;
    }

    throw {
      status: 500,
      message: "Something went wrong",
      reason: error,
    };
  }
};

【讨论】:

    猜你喜欢
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    相关资源
    最近更新 更多