Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript error stops code execution

Whenever an error occurs inside an event handler, it stops code execution entirely so the second event callback isn't called.

For example:

$(function() {
    window.thisDoesntExist();
}
$(function() {
    //Do something unharmful and unrelated to the first event
}

You can easily solve the problem in this (simplified) example by adding try/catch in both anonymous functions, but in reality these functions often add several other event handlers which in turn would require try/catch. I end up with very repetitive code stuffed with try/catch blocks.

My projects has a modular design where each feature is in a different JS (and gets concatenated during a build process). I'm looking for a more generic way to handle errors inside each feature so that the error doesn't stop code execution of the other features.

I already tried following solutions: - window.onerror (even if you return true in this function, code execution is stopped) - $(window).error() => deprecated and code execution stops

like image 437
Webberig Avatar asked May 24 '13 07:05

Webberig


1 Answers

You could create a helper function to prevent duplication of the same boilerplate code.

function tryFunction(f, onerror) {
    try {
        if (typeof f == 'function') {
            return f();
        }
    } catch (e) {
        return onerror(e);
    }
}

$(function() {
    var result = tryFunction(window.thisDoesNotExist, function (error) {
        alert('Whoops: ' + error);
    });
});

I created a little demonstration. It's slightly different but the same idea.

like image 151
Bart Avatar answered Nov 15 '22 01:11

Bart