繁体   English   中英

Typescript 中的太多尝试捕获

[英]too many try catch in Typescript

我正在使用 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...

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

您可以创建自己的异常,并在需要时抛出它们,并且只使用一次 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
  }
}

你可以创建一个 function 来获取我认为的数据

export async function fetchRetry(url: string, options: any) {
  let error = null;
    try {
      const response = await fetch(url, options);
      const { status } = response;
      if (response.ok) {
        try {
          return await response.json();
        } catch (error) {
          // for response that has no body to parse like DELETE method
          return true;
        }
      }
      if (status === 406) {
        error = new ObsoleteApiError("API Deprecated");
      }

      if (status === 503) {
        error = new MaintenanceApiError("We are currently undergoing maintenance");
      }

      if (status >= 400 && status < 500) {
        // code to log to flurry
        if (status === 400) {
            error = new BadRequestError('Bad Request Error')
        }
        error = new ClientApiError(
          `Invalid input on :${url}`,
          await response.json()
        );
      }

      if (status === 403 || status === 401) {
        error = new SingleSessionError("You have logged into another device");
        await AccessToken.getNewTokens();
      }

      break;
    } catch (err) {
      console.log(err);
      if (!error) {
        console.log(`request error based on url: ${url}`);
        console.log(err.name);
        error = err;
      }
    }
  if (error) {
    throw error;
  }
  throw new ServerApiError("Server error");
}

然后你只打电话

const {data} = fetchRetry("http://blabla", options)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM