Eric Isakson
Eric Isakson

Reputation: 93

How do I recover from require failure in a dojo plugin?

I have a requirement where I need to pass a list of modules to a plugin and have it load the modules and perform some work. If I'm passed a module I can't load, I should report an error and move on to the rest of the list. I'm stuck because I can't figure out how to recover from the require failure for the bad module. Is there some other technique I can use to meet this requirement? Here is an example that distills the problem down without all of my other requirements, I need to recover from the failure to load my/thing2:

define("my/thing", [], function() {
    return 'thing';
});
define("my/loader", [], function() {
    return {
        load: function(mid, require, callback) {
            console.log('inside load', arguments);

            // is there some way to recover when this require fails
            // or some other technique I can use here?
            try {
                require([mid], function(mod) {
                    console.log('inside require, mod=', mod);
                    callback(mod);
                });
            }
            catch (error) {
                // never gets here, when the require fails everything just stops
                console.log(error);
                callback("failed to load " + mid);
            }
        }
    }
});

require(["my/loader!my/thing"], function(loaded) {
    console.log('loaded', loaded);
});

require(["my/loader!my/thing2"], function(loaded) {
    console.log('loaded', loaded);
});

Upvotes: 4

Views: 443

Answers (1)

Bucket
Bucket

Reputation: 7521

If you're strictly required to ignore invalid or faulty modules and continue on to the next, use dojo/_base/lang::exists() before tossing them into a require statement:

require(['/dojo/_base/lang', 'dojo/text!my/thing2'], function(lang, myThing2) {
    if(lang.exists(myThing2)) {
        //success
    } else {
        //failure
    }
});

Upvotes: 1

Related Questions