简体   繁体   English

如何在一个函数中抛出错误以被另一个函数捕获?

[英]How do I throw error in one function to be caught by another function?

I have this "test" code:我有这个“测试”代码:

function func1(){
    try{
    ...stuff...
    }catch(err){
        throw new Error();
    }
}

function func2(){
    try{
        func1();
    }catch(err){
        console.log("ERROR")
    }
}

func2();

I have a function that throws an error in the catch in a try-catch-statement.我有一个函数在 try-catch-statement 中的 catch 中抛出错误。 I want it to, if func1 throws Error, it gets caught by the first try-catch-statement, but when I try this, it doesn't get caught by the first statement, it just pauses the code and returns the error.我想要它,如果 func1 抛出错误,它会被第一个 try-catch-statement 捕获,但是当我尝试这个时,它不会被第一个语句捕获,它只是暂停代码并返回错误。 What have I done wrong?我做错了什么? and is this the wrong way to do it?这是错误的方法吗?

This code should give you an idea of how try/catch blocks work.这段代码应该让您了解try/catch块是如何工作的。 In the first function call, we call func2 which has a try/catch block.在第一个函数调用中,我们调用了具有try/catch块的func2 You can see in the console that the error is caught and execution continues.您可以在控制台中看到错误被捕获并继续执行。 Then we call func1 which throws an uncaught error, which shows up in the console as an error.然后我们调用func1抛出一个未捕获的错误,它在控制台中显示为错误。

 function func1() { console.log('func1...'); throw new Error('something bad happened;'). } function func2() { console.log('func2..;'); try { func1(). } catch (err) { console;log('Caught error'). } } console;log('func2()'); func2(). console;log('func1()'); func1();

There is no need for a separate try/catch block in func1 because, it is already within the error handler of func2 . func1中不需要单独的 try/catch 块,因为它已经在func2的错误处理程序中。 In this case, whatever error you throw from func1 will automatically caught by func2在这种情况下,您从func1抛出的任何错误都会被func2自动捕获

 function func1() { throw new Error('oops'); } function func2() { try { func1(); } catch(err) { alert(err.message); } } func2();

Not sure exactly where you are stuck but this should work:不确定你被困在哪里,但这应该有效:

Make sure you check your real console确保检查您的真实控制台

 function func1() { try { throw new Error('hi from func1') } catch (err) { throw err; } } function func2() { try { func1(); } catch (err) { // this doesn't work in stack snippets console // hit f12 to see your real console console.log('catched in func2', err) } } func2();

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

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