Reputation: 1261
I'm using my first global error handler for ajax calls where I get the error information, send it off to a PHP script and then log the results:
$(document).ajaxError(function(event, request, settings){
//get the error and log the results
var file = window.location.href;
var verbose_error;
verbose_error = 'Ajax error: ' + request.responseText + '\n\n';
verbose_error += 'Status:' + request.status + '\n\n';
verbose_error += 'Status Text:' + request.statusText + '\n\n';
verbose_error += 'Url: ' + settings.url + '\n\n';
verbose_error += 'Data: ' + settings.data + '\n\n';
verbose_error += 'Data Type: ' + settings.dataType + '\n\n';
$.post(getUrl() + 'error/log-ajax-error',{file : file,verbose_error : verbose_error},function(o){
});
});
When I do error handling for my PHP scripts, I can get a stack trace to see which function actually caused the error. Assuming that all of my ajax calls are performed within other functions, can I get the name of the function that caused the problematic ajax call?
For example, in the code below, if the $.post returns an error, I'd like to be able to access the name badAjaxCall, and then put it in my log to help with debugging.
function badAjaxCall() {
$.post(url,data,function(o){
});
}
Upvotes: 0
Views: 312
Reputation: 3568
Create a new Error()
and get the stack
. Yo will have all details.
As long as you don't throw
the error, the end user will not notice it.
You could also do throw error
, if you want a feedback in the browser console.
function foo() {
baz();
}
function baz() {
foobar();
}
function foobar() {
var error = new Error();
alert(error.stack)
}
foo();
In case of async, it is a bit different.
If you create the error in the XHR handler you wont get any stack.
So you have to create the error before sending the XHR and then getting the stack (if needed) in the XHR handler.
function foo() {
baz();
}
function baz() {
foobar();
}
function foobar() {
var error = new Error();
//setTimeout represent your XHR call
setTimeout(function() {
alert(error.stack)
}, 100)
}
foo();
In your case, that would be something like:
function ajaxCallWrapper(url, data, handler) {
//never call direct $.post
//instead always call this function to do an xhr call
var error = new Error();
$.post(url, data, function(o){
if(o.error) {
//in case of error, show the stack
alert(error.stack);
return;
}
//otherwise call the handler
handler(o);
});
}
function badAjaxCall() {
ajaxCallWrapper(url,data,function(o){});
}
function normalAjaxCall() {
ajaxCallWrapper(url,data,function(o){});
}
Upvotes: 2