JavaScript 如何在不使用try/catch块的情况下重新编写代码示例
执行JavaScript代码时几乎肯定会出现错误。这些问题可能由程序错误、输入错误或程序逻辑问题引起。但是,所有错误都可以解决,为了解决这些问题,我们有不同的语句可以使用,但最常用的是“try和catch”。
然而,如果一个方法包含在执行过程中可能产生异常的代码,我们通常会用try-catch块来处理异常。
示例1: 不使用try-catch语句
Javascript
console.log("Start of program");
helloWorld;
console.log("Another program execution");
输出:
Start of program
Uncaught ReferenceError: helloWorld is not defined
示例2: 使用try-catch语句
Javascript
try {
console.log("Start of program");
helloWorld;
}
catch (err) {
console.log("Error has occurred" + err.stack);
}
console.log("Another program execution");
输出结果:
Start of program
Error has occurred ReferenceError: helloWorld is not defined
Another program execution
在上面的示例中,该方法在执行过程中抛出异常,因为有一个try-catch块进行异常处理,所以程序可以成功执行而不会异常终止!
1. 何时适合使用Try-Catch?
如果您希望隐藏错误信息或为用户创建自定义错误,并且它还具有隐藏技术性错误信息的优势,这些信息对于那些无法理解它们的人来说是太复杂的,那么应该使用try-catch语句。
在您认为出现的错误是出于您无法控制的原因时,最好在代码的某些部分使用try-catch。
2. 何时不应使用Try-Catch?
如果您知道错误可能发生,那么不应该使用try-catch语句,因为您更愿意调试问题而不是掩饰它。
让我们看一个示例来更好地理解这一点!
示例1: 嵌套的try-catch
Javascript
async function anyFunction() {
try {
const result = await fetch("http://author.com");
try {
const another = await fetch("http://huihuihui.com");
} catch (anotherError) {
console.log(anotherError);
}
} catch (e) {
// Some other error handling
}
try {
const anotherResult = await someOtherAsync();
} catch (errorFromAnotherResult) {
// Some other error
}
}
为什么要避免写太多的try-catch语句?
每天,开发人员编写代码,我们需要检查其错误,而你在代码的各处都编写了try/catch块以防止程序崩溃。由于你想要标准化错误管理,有时候可能会过分使用。
类似于”Try / Catch”的语句随处可见…它们甚至可能嵌套或链接在一起,从而导致代码变得 重复 和 冗余 ,而且你也不想依赖外部库的错误格式(或自定义错误格式)。
你不得不承认这是繁琐、重复和枯燥的。
但是,正如我们将在下面看到的,通过创建一个中间件(使用一小段代码),我们可以通过将异步代码封装到一个简单的中间件(或者可以说是实用函数)中来实现更大更强大的功能。
让我们看看我们的代码内部发生了什么!但首先,让我们来看看我们的 getResult 函数:
Javascript
async function getResult(num: number):
Promise<number | Error> {
if (num === 0) {
throw new Error("Error found!")
}
return num;
}
基本上,此函数接受一个数字,并返回一个返回数字或错误的Promise。
如果数字为零,它将返回错误,否则将返回数字。
输出:
输入:0
Error found!
输入:1
1
现在,为了以更功能性的方式来完成这个任务,我们创建了一个实用函数名为“ tryToCatch ”,这个函数接受一个函数和参数,并尝试在try-catch块中运行我们的函数,它会将错误返回为null,然后返回我们函数的结果,否则它将返回一个错误。
Javascript
const tryToCatch = async (fn: Function, ...args: any) => {
try {
return [null, await fn(...args)];
}
catch (err) {
return [err];
}
};
让我们使用我们的新实用函数来重构我们的代码,通过将我们的函数包裹在名为“tryToCatch”的实用函数中来移除try-catch块
示例1: 使用传统的try-catch语句。
Javascript
async function run() {
let result;
try {
result = await getResult(0);
} catch (error) {
console.log("Error handled");
}
console.log({ result });
};
输出结果:
Error handled
示例2: 使用实用函数重构相同的代码。
Javascript
async function run() {
const [error, result] = await tryToCatch(getResult, 1);
if (error) {
console.log(error);
return error;
}
console.log({ result });
};
输出结果:
{result:1}
现在我们可以处理错误并且可以保持结果控制台的正常日志记录。除了通常的try / catch块之外,您现在可以使用该类似顺序的样式来处理错误。
极客教程