javascript - 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...
但我不确定我建议的想法是好是坏。肯定的是,原来的有问题。不是吗?
解决方案
您可以创建自己的异常,并在需要时抛出它们,并且只使用一次 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
}
}
推荐阅读
- vue.js - 如何在 VueJS 模板中声明具有动态名称和动态组件的插槽列表?
- c++ - 将类重新定义为不同类型的符号
- java - log4j 从哪里选择保存日志的驱动器
- c# - 两个 azure web api 如何在 azure 中通信
- java - 为什么局部变量存储在java的堆栈内存中
- c# - 如何从非控制台 ASP.Net 应用程序中捕获标准输出
- python - 如何在 python 中更改垂直对齐列?
- vert.x - Vert.x 响应路径处理程序示例
- c# - Response.Redirect 并导致 System.Threading.ThreadAbortException?
- visual-studio - 错误:“Visual Studio Community 2017 产品已安装在此文件夹中。需要选择其他位置。”