itsmikem
itsmikem

Reputation: 2168

How to stop propagation of a nested try/catch error in javascript?

function1() outputs:

a
d
b

What I would like is that if function2 errors, to not return to function1, and leave the output at:

a
d

Is this possible? I'm thinking I could reference a returned boolean (errored or not) in a finally block, but I'm wondering if there is a better solution.

function1(){
    try {
             console.log("a");
             function2();
             console.log("b");
         } catch (e){       
             console.log("c");
         }
}
function2(){
    try {
             if(...) throw new Error();
         } catch (e){
             console.log("d");
         }
}

Upvotes: 2

Views: 5131

Answers (2)

zamashkin
zamashkin

Reputation: 11

Hack that you can use is to rethrow an error with message and then check for this message

function1() {
    try {
        console.log("a");
        function2();
        console.log("b");
    } catch (e) {
        if (e.message !== 'rethrowed error') {
            console.log("c");
        } 
    }
}

function2() {
    try {
        if (...) throw new Error();
    } catch (e) {
        throw new Error('rethrowed error')
    }
}

Upvotes: 0

spozun
spozun

Reputation: 882

I think you really want your code to return, and that you should look at a structural solution to get the output you want.

To ensure function1 halts execution, have function2 throw an Error. You can either NOT catch errors in function2 and let them bubble up, or you can throw an error from the catch block in function 2:

function2(){
    try {
             if(...) throw new Error();
         } catch (e){
             console.log("d");
             throw new Error();   //do this!
         }
}

Also, I realize you may be looking for some more control than that, so you could throw something from function2 to function1 to make it more clear like below:

function one(){
    try {
             console.log("a");
             two();
             console.log("b");
         } catch(e){       
             console.log(e == 7);  //this is true!
         }
}

function two(){
    try {
             if(true){ throw new Error();}

         } catch(e){
             console.log("d");
             throw 7;
         }
}

one();

Upvotes: 2

Related Questions