[SOLVED] How to use common try-catch for processing every given function in Javascript?

Issue

These are some of my functions, I need to write a common function to see if functions are running without error. I tried with try/catch method. But I could only do that individually on each function.

function fisrt(){
 console.log("First");
};

function second(){
 console.log("Second");
}

function third(){
 console.log("Third");
}
fisrt();
second();
third();

I was writing each function inside the try-catch. Is there a way I can write a common try-catch for all the functions.

try {
     (function first() {
       console.log("ffgdf")
    })();

 }catch (e) {
      console.log( "won't work" );
    }

Solution

You could define a wrapper function, that takes your desired function as a parameter, and wraps it in a try catch.

function wrapper(fn) {
    try {
        fn();
    } catch(error) {
        console.error(error);
    }
}

Then given your original functions:

function first() {
    console.log("First");
};

function second() {
    console.log("Second");
}

function third() {
    console.log("Third");
}

You can test each one by using your wrapper function:

wrapper(first);
wrapper(second);
wrapper(third);

Without needing to add try catch to each function.

Answered By – Steve Vaughan

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *