首页 > 解决方案 > Typescript 中的 try catch 太多了

问题描述

我正在使用 TypeScript 在服务器端工作。我有一个问题。使用 jwt,我必须捕获几种类型的错误。但是每一行都有自己的自定义错误要发送给客户端。这意味着每一行都有自己的 try-catch 子句。它看起来并不酷。而且我不知道这是否是好的做法。(我有 60% 的把握它可能不好……)

例子:

try {
  dowork();
} catch(err) {
  throw NouserError;
}

try {
  dowork2();
} catch(err) {
  throw InvalidTokenError;
}

try {
  dowork3();
} catch(err) {
  throw blablaError();
}

...and more and more...

我正在考虑像下面这样转换。通过函数内部的移动try-catch块,函数在发生错误时不会返回其结果。建议:


const val1 = dowork();
if(!val1) {
   throw NouserError;
}

const val2 = dowork2();
if(!val2) {
   throw InvalidTokenError;
}

const val3 = dowork3();
if(!val3) {
   throw blablaError();
}

...and more and more...

但我不确定我建议的想法是好是坏。肯定的是,原来的有问题。不是吗?

标签: javascripttypescripterror-handling

解决方案


您可以创建自己的异常,并在需要时抛出它们,并且只使用一次 try() 并检查异常的类型

try {
  myroutine(); // may throw three types of exceptions
} catch (e) {
  if (e instanceof TypeError) {
    // statements to handle TypeError exceptions
  } else if (e instanceof RangeError) {
    // statements to handle RangeError exceptions
  } else if (e instanceof EvalError) {
    // statements to handle EvalError exceptions
  } else {
    // statements to handle any unspecified exceptions
    logMyErrors(e); // pass exception object to error handler
  }
}

推荐阅读