让我们清理一下:丑陋的尝试捕获!
让我们清理一下:丑陋的尝试捕获!
让我们清理一下:丑陋的尝试捕获!
我们都经历过这种情况。我们都用过await
方法async
,却忘了把它们包装起来,try-catch
结果被人骂了一顿Unhandled Error
😱
但并非只有这些aysnc
方法可能会抛出错误。也许我们使用了会抛出错误的第三方库,或者我们在设计代码库时故意抛出错误,以便将错误处理向上层传递。
因此,我们继续将对可抛出方法的调用包装到try-catch
块中。
完美!😍
🤔 或者是吗?
在代码库中,你期望方法能够工作,但这throw
可能会使你的逻辑被包裹在try-catch
块中。这也会导致其他代码设计问题。
请看下面的例子:
try {
const myVar = myThrowableMethod();
} catch (err) {
console.log(err);
}
// Wait, there's an error here:
console.log(myVar);
// myVar doesn't exist outside of the try scope.
如上所示,该myVar
变量在代码块之外不存在try
。但我们需要这个值来继续我们的逻辑!
所以现在我们需要做一些不同的事情。
怎么样:
try {
const myVar = myThrowableMethod();
const newVar = manipulateMyVar(myVar);
const response = sendApiRequest(newVar);
return respponse;
} catch (err) {
console.log(err);
}
🤮!
不,我们别这么做。
现在我们所有的逻辑都包裹在try
代码块里了。这太丑了。
而且,如果任何后续方法调用抛出异常,我们确定要用同样的方式处理它们吗?可能吧,但很可能不行!
好的,让我们尝试一些别的东西......
let myVar;
try {
myVar = myThrowableMethod();
return respponse;
} catch (err) {
console.log(err);
}
const newVar = manipulateMyVar(myVar);
const response = sendApiRequest(newVar);
这样稍微好一点,但仍然不够完美。它仍然很丑陋,因为myVar
必须在不同的作用域中声明,然后几乎立即初始化。当myThrowableMethod
抛出异常时,它也会带来问题,因为执行会继续并尝试使用myVar
!
🐛 警报!
我可以继续,给出更多这些try-catch
块可能出现代码设计、可读性和可维护性问题的情况。
相反,我会向您提供一个解决方案!
解决方案🚀
我编写了一个小型库来解决这个问题:
让我们欢迎no-try来到现场。🎉
啥no-try
?😱
no-try
是一个小型库,它可以try-catch
从您的代码中提取内容,提高代码的可读性和可维护性,同时帮助改进代码设计。
它公开了两个功能,noTry
后者noTryAsync
解决并返回 Promises 的结果。
不相信?我们来详细看看。
要安装它,只需运行npm i --save no-try
然后将其添加到您的文件中:
在 TypeScript 中;
import { noTry } from "no-try";
在 JS 中:
const noTry = require("no-try").noTry;
现在,让我们重构上面的例子来使用no-try
。
const { result, error } = noTry(() => myThrowableMethod());
if (error) {
// Handle error
return;
}
const newVar = manipulateMyVar(result);
const response = sendApiRequest(newVar);
🎉🎉🎉
这样不是更干净吗?
如果您有一个标准错误处理函数,您可以提供该函数noTry
,如果发生错误它将为您调用它!
function myCustomErrHandler(error) {
// Do something to handle error
}
const { result, error } = noTry(() => myThrowableMethod(), myCustomErrHandler);
if (error) {
return;
}
const newVar = manipulateMyVar(result);
const response = sendApiRequest(newVar);
就是这样!
我们try-catch
从代码中删除了块,防止了与块范围变量相关的问题,同时也使我们的代码更具可读性,而不会牺牲我们想要的处理错误的灵活性。
您可以在GitHubno-try
上阅读更多内容。
现在去清理你的代码!
如果您有任何疑问,请随时在下面提问或在 Twitter 上联系我:@FerryColum。
鏂囩珷鏉ユ簮锛�https://dev.to/coly010/let-s-clean-up-ugly-try-catches-5d4c