requiredjs fall to load fallback - javascript

When using requirejs, we do this:
require(['jquery','bootstrap','history','nanoscroller','noty','noty-theme','bootbox'],function(){
//run code
}
But how can I know when requirejs fail to load any of the plugin and show an alert box with message?

Pass a callback function as the third parameter and that will be called if one of the dependencies fails to load.
require(['jquery','bootstrap','history','nanoscroller','noty','noty-theme','bootbox'],
function(){
//run code
},
function (err) { // callback for dependency load failure
alert(err);
}
);
See the documentation for more details.
Note you can also use a global error handler. The following is an excerpt from the documentation:
To detect errors that are not caught by local errbacks, you can override requirejs.onError():
requirejs.onError = function (err) {
console.log(err.requireType);
if (err.requireType === 'timeout') {
console.log('modules: ' + err.requireModules);
}
throw err;
};

Related

writeFileSync doesn't callback

I am using writeFileSync function to write a file locally, the file does get written, however, the callback function is never called.
I did some googling, some other post are having the issue that it's either 1) passing the content went wrong or 2) having two write function at the same time.
My problem is that there are some other places in my code that is using the writeFileSync, but they are on different routes (not sure if this is the right terminology, localhost:port#/differentroutes <- something like this). I am testing only on my own route so those write functions shouldn't even be called.
Here is my code:
if(!fs.existsSync(dir)){
fs.mkdirSync(dir)
}
//content is just a string var I swear it's just a string
fs.writeFileSync('./pages/SubmissionProcess.html',content,function(err){
if(err){
throw err
}else {
console.log("YES")
}
})
I never see this "YES" nor error in my console even tho the file is already written....
Write file sync doesn't take a callback :D
Take a look at the documentation :
https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options
The parameters are (path, data, options)
If you want to check if the file actually wrote, you can read file sync after writing it or check the last time the file was updated. Otherwise, you should try using the async approach.
All of the synchronous methods throw rather than passing an error to a callback.
try {
fs.writeFileSync('./pages/SubmissionProcess.html', content);
console.log('YES');
} catch (e) {
console.error(e);
}

Catch plugin error javascript

I'm using a plugin and I want to handle the errors throws. In special occasions, my script gets error and the cause is a line of code in the plugin:
...
if (!element) {
throw new Error('Container does not exist: ' + container);
}
...
Plugin failing its function is not a problem, but it stops the rest of my script (which is a problem). So I wanted to use try{}catch(e){} to avoid my script stopping.
<script src="plugin.js"></script>
<script>
//This is my script structure
var object = $('#element');
doSomething();
function doSomething(){
try {
//Here I call the plugin function...
object.pluginAction(options);
} catch(err) {
//Here's the code I want to exec if plugin function fail
console.log('Plugin error: '+err);
}
</script>
But this doesn't work. I still get the error in chrome console and no log and script crashes... How can I handle that error without editing the plugin source?
Thank you

Handling prerequsites load failure in RequireJS require function

I'm using RequireJS for AMD. Using this code I execute my function after ensuring the module1 is loaded:
require(['module1'], function (module1) {
if (module1) {
// My function code...
}
);
In some cases the module1 is not available (mostly because of access security). I want to handle what happens if module1 failed to load. Using some code like:
require(['module1'], function (module1) {
if (module1) {
// My function code...
}
)
.fail(function(message)
{
console.log('error while loading module: ' + message);
}
or maybe the require function accepts another parameter for module load failures?
So the question is, how can I handle if the required module failed to load?
See RequireJS API document: http://requirejs.org/docs/api.html#errors.
require(['jquery'], function ($) {
//Do something with $ here
}, function (err) {
//The errback, error callback
//The error has a list of modules that failed
var failedId = err.requireModules && err.requireModules[0];
if (failedId === 'jquery') {
//undef is function only on the global requirejs object.
//Use it to clear internal knowledge of jQuery. Any modules
//that were dependent on jQuery and in the middle of loading
//will not be loaded yet, they will wait until a valid jQuery
//does load.
requirejs.undef(failedId);
//Set the path to jQuery to local path
requirejs.config({
paths: {
jquery: 'local/jquery'
}
});
//Try again. Note that the above require callback
//with the "Do something with $ here" comment will
//be called if this new attempt to load jQuery succeeds.
require(['jquery'], function () {});
} else {
//Some other error. Maybe show message to the user.
}
});

Catching module loading errors and processing them

I am trying to load some content using require.js. If the content doesn't exist I'd like to catch the error and notify the user.
In firebug I can see two errors:
"NetworkError: 404 Not Found
...and then a few seconds later:
var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#
Load timeout for modules: modules/messages/messages
http://requirejs.org/docs/errors.html#timeout
My code resembles:
require([path], function(content){
//need to catch errors as this will not be called;
});
How would one bind to requirejs events? Any idea?
It is also possible to use errbacks to have customized error handling appropriate to the specific use of require. Errbacks are documented here http://requirejs.org/docs/api.html#errbacks. Basically, you can add to require a function to be called if the load fails. It comes right after the function to be called if the load is successful.
Chin's case could be handled as:
require([path], function(content){
//need to catch errors as this will not be called;
}, function (err) {
//display error to user
});
Here's an example that tries loading from multiple places:
require([mode_path], onload, function (err) {
if (mode_path.indexOf("/") !== -1)
// It is an actual path so don't try any further loading
throw new Error("can't load mode " + mode_path);
var path = "./modes/" + mode_path + "/" + mode_path;
require([path], onload,
function (err) {
require([path + "_mode"], onload);
});
});
In this example onload would be the function called once the required code loads, and mode_path is a string identifying the mode. What you see there is code attempting to load a mode module for an editor from 3 different locations. If mode_path is foo, it will try to load foo, then ./modes/foo/foo and then ./modes/foo/foo_mode.
The example at requirejs.org shows how one might handle a case where they want to try multiple locations for a resource they want to make available with a well-known identifier. Presumably the entire code-base in that example requires jQuery by requiring "jquery". Whatever location jQuery happens to be located at, it becomes available to the whole code-base as "jquery".
My example does not care about making the mode known to the entire code-base through a well-known identifier because in this specific case there's no good reason to do so. The onload function stores the module it gets into a variable and the rest of the code base gets it by calling a getMode() method.
set the requirejs onError function:
requirejs.onError = function (err) {
if (err.requireType === 'timeout') {
// tell user
alert("error: "+err);
} else {
throw err;
}
};
If you want to setup an event you could bind to and trigger a global object. Such as:
$("body").bind("moduleFail",function(){
alert("Handling Event")
});
requirejs.onError = function (err) {
if (err.requireType === 'timeout') {
$("body").trigger({type:"moduleFail",err:err})
} else {
throw err;
}
};
require(["foo"],function(foo){
alert("loaded foo" + foo)
})
Did you try to override the requirejs.onError like shown here?
It worked for me after setting catchError as true like this:
require.config({catchError:true});
before calling any define() or require() functions.
You can use the requirejs.onError function as :
requirejs.onError = function (err) {
if (err) {
//Reload
}
else {
throw err;
}
};
You can also use err.requireType to catch specific errors like timeouts

How do I capture JavaScript errors generated in a page fetched by PhantomJS?

I have a PhantomJS script that loads a local HTML file, injects some javascript files, then executes some javascript in the context of the page. The javascript that runs generates an exception, but I only get output from the console, which doesn't seem to distinguish between an error and a normal log and doesn't have file, line numbers or a stacktrace.
What I need is a way to capture or otherwise distinguish these errors. I have already tried:
Wrapping my PhantomJS script in a try-catch
Result: nothing is thrown far enough to be caught by this
Define a window.onerror function
Result: nothing happens. WebKit does not implement an onerror event on the window
I would prefer to be able to retrieve the error object itself so that I can retrieve the stacktrace.
I think there were issues with window.onerror not properly working in WebKit (https://bugs.webkit.org/show_bug.cgi?id=8519). Don't know if this has been fixed at all, and if so, if the QT WebKit version is already up-to-date.
However, you should be able to catch the exceptions thrown in your code. If you are using something like webPage.evaluate(...)to run your code, you cannot wrap the complete call in a try/catch block, since the script is evaluated in a different context and the errors will not appear in the main execution context. Insteadyou will need to catch the errors in page execution context. Unfortunately, there is no way of accessing any functions defined in the main context, we therefore have to explicitly write the wrapping code around your code to be executed.
The following is a modified example of the phantomwebintro.js file as included in the PhantomJS source. It loads an HTML page, inserts a script and then runs some code in the page context (here with a line throwing a type error). This code is wrapped with a try/catch block and will return the wrapped result or error object to the main context.
...
// Load an HTML page:
page.open("http://www.phantomjs.org", function(status) {
if (status == "success") {
// Inject some scripts:
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
// Run your own code in the loaded page context:
var resultWrapper = page.evaluate(function() {
var wrapper = {};
try {
// Your code goes here
// ...
var x = undefined.x; // force an error
// store your return values in the wrapper
wrapper.result = 42;
} catch(error) {
wrapper.error = error;
}
return wrapper;
});
// Handle the result and possible errors:
if (resultWrapper.error) {
var error = resultWrapper.error;
console.log("An error occurred: " + error.message);
// continue handling the error
// ...
} else {
var result = resultWrapper.result;
// continue using the returned result
// ...
}
...
});
}
});
...
The solution? return true!
// Error tracking
page.onError = function(msg, trace) {
console.log('= onError()');
var msgStack = [' ERROR: ' + msg];
if (trace) {
msgStack.push(' TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
});
}
console.log(msgStack.join('\n'));
// Consider error fully handled
return true;
};

Categories