Problem catching errors occured in jquery ajax method - asp.net

I am using jquery ajax method on my aspx page to call a web method in the code behind.If the call fails,for any reason I would like to catch the error and display a meaningful message to the user.Following is my jquery ajax method code.
$.ajax(
{
type:"POST",
url:"Default.aspx/createitem",
data:JSON.stringify({question : question, answer : ans, url : url, category : cat, maincat : maincat, validfrom : validfrom, validuntil :validuntil}),
contentType:"application/json; charset=utf-8",
dataType:"json",
success:function(msg)
{
alert(msg.d);
//success code goes here
},
Error:function(xhr, status, error) {
// Boil the ASP.NET AJAX error down to JSON.
var err = eval("(" + xhr.responseText + ")");
// Display the specific error raised by the server (e.g. not a
// valid value for Int32, or attempted to divide by zero).
alert(err.Message);
}
});
But in case of any error like 'missing parameter' or something neither the success function nor the error function is getting executed an I had to check the response in firebug.Please could someone tell me what am I doing wrong?
Thanks.

Error:
should be
error:
lowercase

Related

How to catch every exception thrown in a webmethod but without those exceptions interrupting the execution of the program

Is there any way I can make that every exception thrown inside a webmethod go straight to the jQuery Ajax error callback function?
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "MantenimientoNotasCapacidades.aspx/SaveViaWebService",
data: JSON.stringify(params),
dataType: "json",
async: true,
success: function (data) {
},
error: function (request, status, error) {
var response = JSON.parse(request.responseText).d;
var error = JSON.parse(response);
alert(JSON.parse(request.responseText).error.message);
}
});
I know that using JSON.parse(request.responseText).Message should be enough to show the information for that error but all I've got now is that every time an exception is raised the code stops right there , being necessary to keep pressing F10 or F5 to finally be able to see the alert.
I already tried enclosing my code in a 'try' block but I don't see much point in doing that since I can't do much in the 'catch' block as I'd do in a visual basic application where I could use the 'catch' block to show the exception message in a MsgBox.
Is there any way to catch in the error callback function all the exceptions thrown in a webmethod but without them stopping the execution of the code?
Any help would be much appreciated.
P.S. Happy new year!!
Following #cmd.promt's advice, I changed the Response.StatusCode to 500 and created and object(myError) containing the description for the exception that was thrown, then the only thing left to do was to serialize the object and send it back to the client (Here I tried to use Response..Write("{""message"": ""action failed!""}") but for some reason I always ended up getting the same error : "JSON.parse: unexpected non-whitespace character after JSON data" so in the end I decided to go with json.net and forget all about response.Write)
<WebMethod()> _
Public Shared Function SaveViaWebService(lst As List(Of Students)) As String
Try
Catch ex As Exception
Dim httpResponse = HttpContext.Current.Response
httpResponse.Clear()
httpResponse.StatusCode = 500
'I thought that .StatusDescription would be useful but it turned out it didn't
'httpResponse.StatusDescription = ex.Message
Dim myError= New With {.message = ex.Message, .source = ex.Source}
Return JsonConvert.SerializeObject(myError)
End Try
End Function
And with that, the error is correctly sent to the error callback , where the only thing I had to do was to play with firebug and see how the error has been sent
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "MantenimientoNotasCapacidades.aspx/SaveViaWebService",
data: JSON.stringify(params),
dataType: "json",
async: true,
success: function (data) {
},
error: function (request, status, error) {
var response = JSON.parse(request.responseText).d;
var error = JSON.parse(response);
alert(JSON.parse(request.responseText).error.message);
}
});
Thus far, everything is as I as wanted it , except for the exceptions that keep on interrupting the execution of the program. Is that their normal behaviour ?? Aren't they all supposed to go directly to the 'catch' block??

How to process msg returned from jquery.ajax()

I would like to know what are the properties of msg object from jquery.ajax(). I am throwing an exception inside asp.net static function, but I am unable to cast it in javascript.
Thanks for help
You can read the response from your .Net page e.g.
$(function(){
$.ajax({
type: 'POST',
url: "test.aspx",
data: "ref=test",
success: function(r) { },
error: function(r) { alert(r.toString()); }
});
});
You can then read the error message and do the necessary steps..
If you have exception in the Server-Side, then JavaScript couldn't catch the Exception cause JavaScript is in the Client-Side.
You can catch the exception by yourself in Server-Side and send a custom error message to Ajax "success function" to handle the error(Exception) you thrown

In ASP.NET with JQuery, how would you define and handle exceptional conditions

I use $.ajax to call a .asmx to get JSON data back. The server side process will meet some exceptional conditions which will give back to client error response for displaying error message.
How would you design the error hanlding mechanism? I mean what would you make server side retrun and let client handle the error?
Thanks.
If it's just an error message (a string), then you can just return that string and set the status to 500 so jQuery recognizes it's not a successful request. Then just use your error handler (or a global .ajaxError() handler for all requests) to do what you want with that message.
For example a simple way to handle all errors like this (instead of per-$.ajax() call) would be:
$(document).ajaxError(function(e, xhr) {
alert("There was an error, server responded with: " + xhr.responseText);
});
ther's an error handler in jquery just like the success function, you need to handle it:
function CallWebService(ParentPage) {
$.ajax({
type: "POST",
url: "../Admission/AdmissionService.asmx/LoadLocations",
data: "{'ParentPage':'" + ParentPage + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('.innerHospitalCensusdiv').html(data.d);
BindSelectLocation();
},**error: function(ex){
//handle error here
}**
});
}

why does the 'error' function of $.ajax execute even when the request to invoke a webmethod succeeds?

I am using jquery ajax method to invoke a webmethod upon clicking a 'span'.This is webmethod is in one of my aspx pages and I am invoking it from the master page using the following code.
$(document).ready(function(){
$("#btn").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/removedata",
data:"{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function(msg) {
$("li#search").removeClass('current');
$("li#search").addClass('hide');
$("#tabnew").addClass('hide');
window.location="Result.aspx";
},
error:function(xhr, status, error) {
alert("error");
//var err = eval("(" + xhr.responseText + ")");
// Display the specific error raised by the server
//alert(err.Message);
console.log(xhr.statusText);
}
});
});
});
when I click the span I can see the webmethod getting invoked(by debugging ),but even before the webmethod starts executing I get the alert 'error' and I see (an empty string) message being logged into the firebug console.
As far as I know the 'error' function gets executed only if the ajax request fails.But I can see the webmethod getting executed.I do not understand why the error function is executing even then.
Could someone please help me with this.
Thanks
The error handler is executed if the server side script returns an error code different than 200. You could use FireBug to inspect what exactly is happening under the covers.

Jquery Ajax call to webservice is failing

Can anyone help? I have an issue with calling a asp.net webservice from jquery.. actually i think it maybe jquery ... as i have a break point and it doesn't arrive in the webservice..
Here is my jquery, the webservice method accepts 2 parameters...
So i setup a simple test to pass in 7 and 7 .. i tried replacing with the word "test" also and it doesn't work..
Basically lands in the error function which displays "sorry error happens" but the err is undefined.
jQuery.ajax({
type: 'POST'
, url: 'CallService.asmx/TempCanMakeCall'
, contentType: 'application/json; charset=utf-8'
, dataType: "json"
, data: "{'reservationNum':'7','completedReservationNum':'7'}"
, success: function(data, status) {
alert(data);
}
, error: function(xmlHttpRequest, status, err) {
alert('Sorry! Error happens.' + err);
}
}
);
Here is the asp.net webservice
[WebMethod()]
public bool TempCanMakeCall(string reservationNum, string completedReservationNum )
{
return true;
}
xmlHttpRequest.responseText has always been my goto when dealing with jQuery AJAX errors.
Try making your ASP.NET function static:
[WebMethod()]
public static bool TempCanMakeCall(string reservationNum, string completedReservationNum )
{
return true;
}
Also note that the returned JSON value is encapsulated in an object named 'd' (ASP.NET specific.) To display your return value upon success, you would need to do this:
success: function(data, status) {
alert(data.d);
}
The jquery ajax call looks fine. I think you need to make sure that the path to "CallService.asmx" is correct. The way it is now, I will only work if the file making the jQuery call is in the same virtual directory as the ASMX.
In your error callback function, you could check 'xmlHttpRequest.status' to get the http code returned from the server. This may give you another clue. If ichiban above is correct, it should be a 404.
You can check the xmlHttpRequest.responseText property. The response text is very probably an html document returned by the server that contains the reason for the error.
If you are using Visual Studio, you can also enable script debugging in Internet Explorer and put the following keyword in your error function: debugger. The browser sees this as a breakpoint and will invoke a debugger (which should be Visual Studio). Now you can check the entire contents of the xmlHttpRequest instance.
For clarity, your error function will then look like this:
function(xmlHttpRequest, status, err)
{
debugger;
...rest of your function...
}

Resources