How to write basic Error Handling when using AJAX JSON - javascript

I'm not as clued up when it comes to back end development but have this small task of adding some error handling to the code that you see below. All I'm looking to do is display the potential error responses to the #results tag if they occur. It only needs to be something basic as the code itself should leave very little room for errors to occur anyway. Any help would be greatly appreciated. Let me know if you have any questions. Thanks for your help.
$('#hierarchyBtn').click(function() {
$.ajax({
url: "libs/php/getHierarchy.php",
type: 'POST',
dataType: 'json',
data: {
geonameId: $('#selHieGeonameId').val(),
},
success: function(result) {
console.log(JSON.stringify(result));
if (result.status.name == "ok") {
var names = result['data'].map(function(geoname){return geoname.toponymName}).join(", ");
$('#results').text(names);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// my error code
}
});
});

If the error you want the display is return by you for instance validation, you can access the erroMessage in the error() callback function but passing errors as parameter and access it with errors.message.
I will display a generic error for all error not related to validation and the validation error if any but, this depends but what you essentially need is to catch the errors that you thrown yourself and display a generic error for anything else, may not be ideal but works
error: function(error) {
// my error code
if(error.statusCode !== 412) {
$('#results').text('A Generic error occured on the server')
}
// Validation error
if (error.statusCode === '412') {
$('#results').text(error.message);
// or $('#results').text(error.errorName)
}
}

Related

Returning a view to an ajax call and replacing html page throws 'appendchild' exception in jquery

I'm making an ajax call like this below where I'm returning a view like this
return View("Finish");
This has the entire html page as a string as the response, so I want to replace the page with it, but when I do I receive an error
Unhandled exception at line 82, column 3 in https://localhost:44368/Scripts/jquery-3.1.1.js
0x800a138f - JavaScript runtime error: Unable to get property 'appendChild' of undefined or null reference occurred
Funny thing is it does set the html so I see the correct page on screen, I just see the exception in JQuery as well!
var options = {
url: scope.enumControllers.saveEvent,
type: "post",
data: viewModel
};
$.ajax(options)
.done(function(response) {
if (response.error === true) {
yb.base.eventAlert(response.message, "error");
} else {
$("html").html(response); // error here trying to set the page to the response html string
}
})
.always(function() {
})
.fail(function(jqXHR, textStatus) {
yb.base.eventAlert("Error saving data. Please contact the help desk.", "error");
});

typeof error comparing to undefined - data is null

I've got a bit of code that's kicking of an error for me - and I can't seem to find a way around it or a good solution in javascript.
var data = new FormData();
$.each(files, function(key, obj)
{
data.append(obj.name, obj.file);
});
data.append('submitCustomizedDatas', 1);
data.append('ajax', 1);
$.ajax({
url: $('#customizationForm').attr('action'),
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
async: false,
success: function(data, textStatus, jqXHR)
{
if(typeof data.errors === 'undefined')
{
$.each(files, function(key, obj)
{
$('input[name="'+obj.name+'"]').addClass('filled');
previewFile($('input[name="'+obj.name+'"]'), obj.file);
});
$('.uploadingfiles').text('Upload Complete!');
}
else
{
$('.uploadingfiles').text('Error while uploading, please refresh the page and try again');
}
$('.myoverlay').click(function(){$(this).remove()});
},
error: function(jqXHR, textStatus, errorThrown)
{
$('.uploadingfiles').text('ERRORS: ' + errorThrown);
$('.myoverlay').click(function(){$(this).remove()});
}
});
This is used for the upload of files on a site I'm making.
This bit of Ajax is kicking off an error in JS console when it hits success. The error is saying 'data is null' at this line:
if(typeof data.errors === 'undefined')
Just curious if this looks right, or if there might be something really obvious I'm missing here.
In javascript, the opening brace placement matters. Your code might not mean what you think it means due to your placement of the opening brace.
Also, the use of .success and .error have been deprecated. Consider using .done or .fail methods.
Typeof null returns an object, so if data.errors is null, your check will fail. Consider doing
if (!data.errors) {
...
}
Lastly, the data being returned from the server might be null. This would cause the null exception that you are seeing. You can debug your application to see if this is the case.
The error you described, "data is null...", is very precise. JavaScript throws an error when you try to access a property from a null object. In this case, you are trying to access the errors property of the data object, which is null in that case (your server is not returning anything).
You should probably verify the data object before making any other assumptions:
success: function(data, textStatus, jqXHR) {
if (data !== null) { // first make sure data is not null
if(typeof data.errors === 'undefined') { // then you can safely trust this line
// ...
}
}
// ...
}
Watching the jqXHR.status could be a way of finding out what is going on with your server.
EDIT: in fact, I recommend always using the server response's status code to check for errors:
success: function(data, textStatus, jqXHR) {
if (jqXHR.status === 200) { // 200 - Success
// Everything went well
// ...
} else {
// Something went wrong
// console.log(textStatus);
if (data !== null) { // first make sure data is not null
if(typeof data.error !== 'undefined') { // // check if the server has returned any error information
// handle specific error
// console.log(data.error);
// ...
}
}
}
}
Hope it helps!

Should you check ajax return data or let javascript throw a error on empty data?

So when handling, for example, the success data in jquery, should you check if the return data has the necessary data like this:
success: function (data) {
if (data.new_rank !== undefined) {
$('._user_rank').html(data.new_rank);
}
}
Or let it fail when it is not present?
success: function (data) {
$('._user_rank').html(data.new_rank);
}
in the previous example you can check if something has changed and needs to be fixt because of the error.
What approach is the best?
It's better you check it, for other code that may be you have in complete or other event. If you didn't, they will not run after error. You can check it this too:
success: function (data) {
if (data.new_rank) {
$('._user_rank').html(data.new_rank);
}
}
jQuery ajax requests provide you a way to handle request errors.
$.ajax(url, {
success: function(data) {
// success
},
error: function() {
// error
}
});
If it's not a request error that you are trying to catch you still should handle error by yourself and not let javascript throw them all the way.
One solution I would say is follow strict data type in $.ajax like dataType: json.
Use success and error handler. And if the return data is anything other than json type it will be handled through error handler.
$.ajax(url, {
dataType: 'json'
success: function(data) {
// success
},
error: function() {
// error
}
});

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
});

ASP.NET MVC HttpException message not shown on client

I'm building a RESTful web api with asp.net mvc, which returns pure json data. On my client, I'm using backbone.js to communicate to it.
My question is, how do I capture the message in javascript? For eg. What if a user has no permission to delete or there was no item matching the id? I've been told to throw http errors instead of custom json.
So my code would be:
[HttpDelete]
public ActionResult Index(int id)
{
if (id == 1)
{
throw new HttpException(404, "No user with that ID");
}
else if (id == 2)
{
throw new HttpException(401, "You have no authorization to delete this user");
}
return Json(true);
}
How do I access the message in my javascript callback? The callback would look like:
function (model, response) {
alert("failed");
//response.responseText would contain the html you would see for asp.net
}
I do not see message i threw in the exception anywhere at all in the data that was returned from the server.
You should use the error callback on the client. The success callback is triggered only when the request succeeds:
$.ajax({
url: '/home/index',
type: 'DELETE',
data: { id: 1 },
success: function (result) {
alert('success'); // result will always be true here
},
error: function (jqXHR, textStatus, errorThrown) {
var statusCode = jqXHR.status; // will equal to 404
alert(statusCode);
}
});
Now there is a caveat with 401 status code. When you throw 401 HTTP exception from the server, the forms authentication module intercepts it and automatically renders the LogIn page and replaces the 401 status code with 200. So the error handler will not be executed for this particular status code.
I just answered this in my question What is the point of HttpException in ASP.NET MVC, but you can actually get that string if you use the HttpStatusCodeResult like this:
In your controller:
return new HttpStatusCodeResult(500,"Something bad happened")
And you can access "Something bad happened" using, say, jQuery $.ajax() like this:
$.ajax: {
url: "#Url.Action("RequestsAdminAjax", "Admin")",
type: "POST",
data: function(data) { return JSON.stringify(data); },
contentType: "application/json; charset=utf-8",
error: function (xhr, textStatus,errorThrown) {
debugger;
toggleAlert('<strong>Error: </strong>Unable to load data.', 'alert alert-danger');
}
},
and errorThrown will contain "Something bad happened".
HTH.

Categories

Resources