How to capture the 500 error message using jquery? - javascript

How can i capture the 500 error message using jquery? I want to keep on checking for the 500 error message for sometime until it changes and time out after 50 sec.
I used the code below to try to capture and check the 500 error message but it doesnt seem to catch the 500 error message. I can see it in the firebug
$.ajax({
statusCode: {
500: function() {
alert(" 500 data still loading");
console.log('500 ');
}
}
});

Dispite the accepted answer mentioned by #Danny, you can also do this in newer versions of jQuery.
var xhr = $.ajax({
url: "somewhere"
});
xhr.fail(function(xhr, textStatus, error) {
// Error handling stuff here ...
});
See Deferred Object.

Are you missing url in $.ajax like the one below
$.ajax({
url: "/path to page",
statusCode: {
500: function() {
alert(" 500 data still loading");
console.log('500 ');
}
}
});

You can check the status in error of ajax post please check the below code.
$.ajax({
.....
success: function (data) {
},
complete: function (XMLHttpRequest, textStatus) {
},
error: function (e, status) {
if (e.status == 404)
alert("404 error");
}
});
Thanks

Related

Api call using Ajax in javascript giving error

i am getting error on calling ajax request with a code 422(unprocessible entity) , i dont understand what is wrong with my code can someone help me to figure out the error
$.ajax({
url: "/api/v3/email_exists",
method: 'POST',
data: {
email: email_entered
},
success: function (response, status) {
if (response.sent) {
showFlashMessage('Email Sent');
alert(response);
}
else {
showFlashMessage('An error occured, please try again latervrfg.', 'error');
}
},
error: function (response, status) {
showFlashMessage('An error occured, please try again later.', 'error');
}
});
url is returning either true or false in case of false it is giving status 422
Try with a full URL e,g https://Path_to _the controller_method

AJAX call doesn't go into "error:" block if the API server returns http 500

I want to implement a retry logic in my javascript code. This is how I'm calling the API:
$.ajax({
url: api_url + 'report',
type: 'GET',
dataType: 'json',
async: false,
tryCount : 0,
retryLimit : 3,
headers: {
"Authorization": "Basic " + btoa(api_username + ":" + api_pass)
},
data: {start: start_date, end: end_date},
success: function(result) {
data = result.results;
console.log("success");
},
error : function(xhr, textStatus, errorThrown ) {
console.log("in error");
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
//try again
console.log("try count:");
console.log(this.tryCount);
$.ajax(this);
return;
}
return;
}
if (xhr.status == 500) {
console.log("still 500");
} else {
console.log("still !500");
}
}
});
So when there are issues with the server and it returns http 500 then still my control in the above JS file doesn't go into the "error:" block and this line: "console.log("in error");" doesnt get printed on the console.
How can I correctly implement a retry logic in my code in case my server returns 500 then it should keep on retrying for some x amount of times?
500 error generally means that something is wrong with backend server. So it doesn't get into error block of client JavaScript. I don't think there is anything you can do. But in general you can always ask backend developers to do better error handling and return apt error response if possible.

Using clearTimeout(x) in ajax call

I am writing codes where the code will do some polling for statistics to the server using AJAX. My web application is getting data from the server every 3 seconds once the server returned the data. It is working good but however, I want to apply clearTimeout(x) function to stop the execution and print something to user when any error occur like "timeout" or "error" triggered by error setting. I managed to search the similar case with me here and this also link. But for some reason my code does not do what I want. Here is what I have so far
var timeoutid = 0;
var myfunc = function() {
$.ajax({
type: "POST",
url: "pull.php",
error: function(xhr, status, error){
if( status==="timeout" || status==="error") {
alert("Timeout or unable to receive statistics!");
clearTimeout(timeoutid);
}
},
success: function(msg){
$('#res').val(msg);
//timeoutid = setTimeout(poll, 3000);
},
complete: function(){
timeoutid = setTimeout(myfunc, 3000);
},
timeout: 5000
});
}
myfunc();
The result of the above when I disable my Internet adapter is it keeps looping and alert me the error without stopping the execution. I don't really know how or where do I put my clearTimeout due to localized variable issue based on what I have read. Not really a master in jQuery in detailed though. Appreciate your kind respond and thank you in advance.
It is because you are again creating a new timer in the complete callback which will get executed in the case of error also
var myfunc = function () {
$.ajax({
type: "POST",
url: "pull.php",
error: function (xhr, status, error) {
if (status === "timeout" || status === "error") {
alert("Timeout or unable to receive statistics!");
}
},
success: function (msg) {
$('#res').val(msg);
},
complete: function (jqXHR, status) {
if (status !== "timeout" && status !== "error") {
setTimeout(myfunc, 3000);
}
},
timeout: 5000
});
}
myfunc();

Status Code repeated throughout the JSP

I have a JSP which contains more than 2500 LoC.
Most of the code contribution in that page is by Javascript& jQuery.
error: function(res) {
ajaxFailed(res);
},
statusCode: {
400: function()
{
alert("Bad Request.");
},
403: function()
{
alert("You are not logged in, or your session timed out. Please login and try again.");
window.parent.location.reload(true);
},
404: function()
{
alert("Not Found.");
}
}
Above code snippet is used > 20 occurences.
Is there any way that I can make it as a common method and invoke in all places.
P.S. So that I can save 300 lines of code
You can use the global ajaxError() method which would only need to be included once in a page.
ajaxError() API Docs
Alternatively create an error handler function and pass it as reference to each of your existing calls:
function myErrorHandler(res) {
ajaxFailed(res);
},
statusCode: {.........}
}
$.ajax({
url:'...',
data: data,
success: function(){},
error: myErrorHandler
})

Trapping Function not defined error in Javascript and jQuery

Okay, I do use firebug to determine when a function is not defined in Dev. What I would like to do in production is show a modal window saying an error has been received which would then redirect them to another page upon click. Not so easy.
Please understand that this function does work and the component that is called works. I am going to misspell the function call on purpose to demonstrate the error I am not receiving thru the jquery ajax function.
I am using .ajaxSetup to set up the default options for several ajax functions that will be running asynch:
$.ajaxSetup({
type: "POST",
dataType: "json",
url: "DMF.cfc",
data: {
qID: 1,
returnFormat: "json"
},
beforeSend: function() {
$('#loadingmessage').fadeIn(); // show the loading message.
},
complete: function() {
$('#loadingmessage').fadeOut(); // show the loading message.
}
}); //end AjaxSetup
The actual ajax call is:
$.ajax({
data: {
method: 'getCurrentIssues'
},
success: function(response) {
nsNewDebtshowDebtIssues(response);
},//end success function
error: function(jqXHR, exception) {
alert("Error running nsNewDebt.showDebtIssues");
}
}) //end getCurrentIssues Ajax Call
The error I forced is that the method run in the success function should actually be nsNewDebt.showDebtIssues. Firebug correctly displays in console the error nsNewDebtshowDebtIssues is not defined but the actual error message for the ajax call does not run, so if an enduser was running the page it would appear the page was hung.
So, In summary I want to know how to track when such an error occurs, preferrable to place in the error section of the .ajaxSsetup but if neccessary in each .ajax call.
It is not an ajax error, so you cannot handle it from the ajaxError method.
You should do a try/catch in the success method.
success: function(response) {
try {
nsNewDebtshowDebtIssues(response);
} catch (ex) {
//exception occured
//alert("Error running nsNewDebt.showDebtIssues");
alert( ex.message + '\n\tin file : ' + ex.fileName + '\n\t at line : ' + ex.lineNumber);
}
}
Before making the call, you can do:
if(typeof nsNewDebtshowDebtIssues == 'function') {
// .. call it ..
}
Well, the error actually occurs after the AJAX call has succeeded (since it comes from your success handler), so the error handler indeed won't be called.
If you want to use the same handler for actual AJAX request errors and for further errors originating from your success handler, you can define a named function and use it both as your error handler and from a try/catch block in your success handler:
function handleError(jqXHR, status, exception)
{
alert("Error running request.");
// Or print something from 'jqXHR', 'status' and 'exception'...
}
$.ajax({
data: {
method: "getCurrentIssues"
},
success: function(response, status, jqXHR) {
try {
nsNewDebtshowDebtIssues(response);
} catch (x) {
handleError(jqXHR, status, x);
}
},
error: handleError
});

Categories

Resources