Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

continue execution after a throw in JS

i have this function in my code and I'm using throw to create meaningful errors (rather than failing silently). However, when i structure my function this way, if i call defineSandbox() with an error, it stops the whole script.

//defineSandbox is in an object, for now i name "myObj"

var defineSandbox = function (sandboxName,SandboxDefinition) {

    //validation
    if(!is.validString(sandboxName)) {
        throw statusMessages.sandbox.invalidName;
    }
    if(!is.validFunction (SandboxDefinition)) {
        throw statusMessages.sandbox.invalidDefinition;
    }

    //...some more validation here

    //...sandbox builder code if validation passes (code wasn't returned)

    registered.sandboxes[sandboxName] = newSandbox;
};

//intentional error, non-string name
myObj.defineSandbox(false);                        

//...and so the rest of the script from here down is not executed  

//i can't build this sandbox anymore
myObj.defineSandbox('mySandbox',function(){...});  

what i would like to have is if one call fails, it gives out an error but still tries to continue to run the script. how do i structure this code so that i can achieve that?

like image 543
Joseph Avatar asked Mar 19 '12 22:03

Joseph


People also ask

Does execution continue after catch JavaScript?

After a try/catch statement in JavaScript, the code will continue executing.

Does throw stop execution JavaScript?

The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.

Do I need to return after throw?

You do not need to put a return statement after throw , the return line will never be reached as throwing an exception immediately hands control back to the caller.

What happens after catch JavaScript?

JavaScript creates this identifier when the catch block is entered. The identifier lasts only for the duration of the catch block. Once the catch block finishes executing, the identifier no longer exists.


6 Answers

Typically, you don't want to continue execution when you manually throw a new error. If you want to have it for a logging purpose, you should consider an self-created internal solution.

However, to catch a thrown error you need to invoke a try / catch statement.

try {
    myObj.defineSandbox(false); 
} catch( ex ) {
    // execution continues here when an error was thrown. You can also inspect the `ex`ception object
}

By the way, you can also specify which kind of error you want to throw, for instance a type error or a reference error like

throw new TypeError();
throw new ReferenceError();
throw new SyntaxError();
etc.

Complete list: MDN

like image 107
jAndy Avatar answered Oct 10 '22 20:10

jAndy


console.error() will not throw an error, but will display an error in your log without halting execution.

like image 27
user2849041 Avatar answered Oct 10 '22 20:10

user2849041


If you would like to report the caught error so that window.onerror will fire, you can dispatch an error event in your catch block:

try {
}
catch (error)
{
    const e = new ErrorEvent('error', {message:'my error', error:error})
    window.dispatchEvent(e)
}

I found this useful for catching and reporting errors in a for loop while still continuing with the loop.

like image 32
Mark Avatar answered Oct 10 '22 21:10

Mark


If you are trying to aggregate all the errors instead of just throwing one of them, then you should create an array of the issues (exceptions) and then throw the array, instead of just the first issue you hit.

like image 40
Bert Lamb Avatar answered Oct 10 '22 21:10

Bert Lamb


You need to catch thrown errors if you want to deal with them nicely. In your example:

//intentional error, non-string name
try {
    myObj.defineSandbox(false);
} catch(error) {
   alert("Error defining sandbox: " + error);
}

And then subsequent code will still continue to run.

like image 43
sargant Avatar answered Oct 10 '22 22:10

sargant


var bear = {};
(function () {
    bear.errorProcesser = function  ( e ) {
        console.log( e );
    }
    bear.define = function  ( name, fn  ) {
        try {
            if( typeof name != "string" || typeof fn != "function"){
                throw new Error ("some error");
            }
            bear[name] = fn;
        } catch (e){
            bear.errorProcesser ( e );
        }
    }
})()
bear.define ( "testfunc", {} );
like image 39
Torrent Lee Avatar answered Oct 10 '22 22:10

Torrent Lee