Joseph
Joseph

Reputation: 119847

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?

Upvotes: 15

Views: 74673

Answers (7)

Mark
Mark

Reputation: 6957

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.

Upvotes: 5

user2849041
user2849041

Reputation: 151

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

Upvotes: 14

Torrent Lee
Torrent Lee

Reputation: 845

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", {} );

Upvotes: 1

sargant
sargant

Reputation: 356

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.

Upvotes: 1

jAndy
jAndy

Reputation: 236022

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

Upvotes: 21

Bert Lamb
Bert Lamb

Reputation: 2327

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.

Upvotes: 2

Bergi
Bergi

Reputation: 664528

Is it just try-catch you're searching for?

Upvotes: 1

Related Questions