Joseph
Joseph

Reputation: 119877

Catch errors from an object in JS

currently i have a module builder. in this condensed version of the script, a body click fires foo() which throws an error. i would like to attach an error handler to the whole module object to catch whatever is thrown from within it, not just during creation, but also in runtime. is it possible?

currently, "foo alert" comes up in the console. i would like to suppress that and let a central logger do the necessary log. in this case, i want to see "logged" instead.

$(function() {

    var moduleCollection = {};

    //creates modules, stores them and returns for reference
    function define(name, def) {
        var newModule = def();              //creates the module object
        moduleCollection[name] = newModule; //store

        //somewhere here, i must attach some sort of
        //error handlers for the module
        //something like:
        newModule.onerror = function(){
            //execute error procedure (like logging)
            console.log('logged');
        }

        return newModule //return as reference
    }

    //a module definition
    var mymod = define('mymod', function() {
        //foo chokes unintentionally and results into an error
        function foo() {throw new Error('foo alert');}

        function start() {
            //a body click calls foo
            $('body').on('click', function() {foo()});
        }
        return {start: start}
    });

    //start module
    mymod.start()

});​

Upvotes: 0

Views: 151

Answers (1)

David-SkyMesh
David-SkyMesh

Reputation: 5171

If you want that, you'll need to add try and catch at each level of code execution.

That is, at "definition" time, in your constructors (if present), in each method body, and in each event handler.

Also, perhaps it's just your example code, but this:

$('body').on('click', function() {foo()});

Could simply be this:

$('body').on('click',foo);

Upvotes: 1

Related Questions