JavaScript 消除由于意外错误而导致一组函数执行不完整

JavaScript 消除由于意外错误而导致一组函数执行不完整

在本文中,我们将尝试通过JavaScript的一个编码示例来理解如何消除由于意外错误而导致一组函数执行不完整。

首先,让我们通过以下启发式部分来理解如何在函数本身内部抛出和捕获错误,这里展示了相应的语法:

语法: 我们可以使用以下语法,在函数中抛出错误,然后在相同的函数中捕获该错误(注意这里使用了箭头函数,用户还可以选择正常的函数声明语法):

let function_name = () => {
    try {
        // error_message is the string value
        throw new Error(error_message); 
    }

    catch(error) {
        // Do something with this error
    }
}

让我们看一下下面的示例,这将帮助我们更好、更高效地理解上述的语法。

示例1: 在这个示例中,我们将简单地创建一个函数(最好是箭头函数),然后在函数内部创建一个try/catch块,在try块内部抛出一个错误,然后在catch块中捕获该错误。

Javascript

<script> 
    let errorMethod = () => { 
        try { 
            throw new Error("Please try again later..!"); 
        } catch (error) { 
            console.log(error.message); 
        } 
    }; 
  
    errorMethod(); 
</script>

输出:

Please try again later..!

现在让我们了解我们的主要任务是如何消除一组函数的不完整执行,因为出现了意外错误,下面是一个编码示例来解释这个问题:

示例2: 在这个示例中,我们将创建多个函数,每个函数将抛出自己对应的错误,我们将在其他方法中捕获这些错误,形成一条方法执行链。

Javascript

<script> 
    let firstErrorFunction = () => { 
        try { 
            throw new Error( 
                "Error thrown by First Function...!!"); 
        } catch (error) { 
            console.log("Catched error in First Function: " 
                + error.message); 
            throw new Error( 
                "Another error thrown by first function...!!"); 
        } 
    }; 
  
    let secondErrorFunction = () => { 
        try { 
            firstErrorFunction(); 
        } catch (error) { 
            console.log("Catched error in Second Function: "
                + error.message); 
            throw new Error( 
                "Error thrown by second function...!!"); 
        } 
    }; 
  
    let thirdErrorFunction = () => { 
        try { 
            secondErrorFunction(); 
        } catch (error) { 
            console.log("Catched error in Third Function: " 
                + error.message); 
        } 
        console.log("No more errors are left for catching..."); 
    }; 
  
    thirdErrorFunction(); 
</script>

输出:

Catched error in First Function: Error thrown by First Function…!!
Catched error in Second Function: Another error thrown by first function…!!
Catched error in Third Function: Error thrown by second function…!!
No more errors are left for catching…

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程