In this article I will explain how to handle errors and exceptions in jQuery AJAX calls and show (display) Custom Exception messages using jQuery Dialog.
There are two types of Exceptions which is caught by jQuery
1. When exception object is in the form of JSON object.
2. When exception object is in the form of plain text or HTML.
I will explain both the types with detailed explanation and also how to display the exception error details in both the cases.
WebMethod for testing both types
In order to test both the cases I have created the following WebMethod which simply tries to convert the received string value to integer.
[System.Web.Services.WebMethod]
public static void ValidateNumber(string number)
{
int no = Convert.ToInt32(number);
}
1. When exception object is in the form of JSON object
In the following HTML Markup, I have created a simple form with a TextBox and a Button which prompts user to enter a Numeric value.
The value entered is passed to the WebMethod using a jQuery AJAX call where it is converts string value to integer.
If it is a valid number then an alert message is displayed inside the jQuery AJAX Success event handler and if an exception occurs in the WebMethod, the thrown exception is caught inside the jQuery AJAX Error event handler and which makes a call to the OnError JavaScript function which processes and displays the exception details.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
body { font-family: Arial; font-size: 10pt; }
#dialog { height: 600px; overflow: auto; font-size: 10pt !important; font-weight: normal !important; background-color: #FFFFC1; margin: 10px; border: 1px solid #ff6a00; }
#dialog div { margin-bottom: 15px; }
</style>
</head>
<body>
<form id="form1" runat="server">
<u>1: When exception object is in the form of JSON object</u>
<br/>
<br/>
Enter Number:
<input id="txtNumber1" type="text"/>
<input id="btnValidate1" type="button" value="Validate"/>
<div id="dialog" style="display: none"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css"
rel="stylesheet" type="text/css"/>
<script type="text/javascript">
$(function () {
$("#btnValidate1").click(function () {
var number = $("#txtNumber1").val();
$.ajax({
type: "POST",
url: " Default.aspx/ValidateNumber",
data: '{number: "' + number + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert("Valid number.");
},
error: OnError
});
});
});
function OnError(xhr, errorType, exception) {
var responseText;
$("#dialog").html("");
try {
responseText = jQuery.parseJSON(xhr.responseText);
$("#dialog").append("<div><b>" + errorType + " " + exception + "</b></div>");
$("#dialog").append("<div><u>Exception</u>:<br /><br />" + responseText.ExceptionType + "</div>");
$("#dialog").append("<div><u>StackTrace</u>:<br /><br />" + responseText.StackTrace + "</div>");
$("#dialog").append("<div><u>Message</u>:<br /><br />" + responseText.Message + "</div>");
} catch (e) {
responseText = xhr.responseText;
$("#dialog").html(responseText);
}
$("#dialog").dialog({
title: "jQuery Exception Details",
width: 700,
buttons: {
Close: function () {
$(this).dialog('close');
}
}
});
}
</script>
</form>
</body>
</html>
2. When exception object is in the form of HTML or plain text
The second case is similar to the first one. In order to receive a Non-JSON response I have just set incorrect WebMethod name in the jQuery AJAX so that it generates an error.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
body { font-family: Arial; font-size: 10pt; }
#dialog { height: 600px; overflow: auto; font-size: 10pt! important; font-weight: normal !important; background-color: #FFFFC1; margin: 10px; border: 1px solid #ff6a00; }
#dialog div { margin-bottom: 15px; }
</style>
</head>
<body>
<form id="form1" runat="server">
<u>2: When exception object is in the form of HTML or plain text</u>
<br/>
<br/>
Enter Number:
<inputi d="txtNumber2" type="text"/>
<input id="btnValidate2" type="button" value="Validate"/>
<div id="dialog" style="display: none"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css"
rel="stylesheet" type="text/css"/>
<script type="text/javascript">
$(function () {
$("#btnValidate2").click(function () {
var number = $("#txtNumber2").val();
$.ajax({
type: "POST",
url: "Default.aspx/UnknownMethod",
data: '{number: "' + number + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert("Valid number.");
},
error: OnError
});
});
});
function OnError(xhr, errorType, exception) {
var responseText;
$("#dialog").html("");
try {
responseText = jQuery.parseJSON(xhr.responseText);
$("#dialog").append("<div><b>" + errorType + " " + exception + "</b></div>");
$("#dialog").append("<div><u>Exception</u>:<br /><br />" + responseText.ExceptionType + "</div>");
$("#dialog").append("<div><u>StackTrace</u>:<br /><br />" + responseText.StackTrace + "</div>");
$("#dialog").append("<div><u>Message</u>:<br /><br />" + responseText.Message + "</div>");
} catch (e) {
responseText = xhr.responseText;
$("#dialog").html(responseText);
}
$("#dialog").dialog({
title: "jQuery Exception Details",
width: 700,
buttons: {
Close: function () {
$(this).dialog('close');
}
}
});
}
</script>
</form>
</body>
</html>
Parsing the received Exception response using jQuery
Here I am explaining the details of the OnError JavaScript function which is called by the Error event handler in both the above case.
This function accepts the following three parameters
xhr – It is the error response object.
errorType – It describes the type of error.
exception – It contains the title of the exception occurred.
Inside this function, I have placed a TRY CATCH block and within the TRY block, the Exception received is parsed to a JSON object and then the details of the exception are displayed using jQuery Dialog Modal Popup.
If an error occurs during the process of parsing the JSON string, it means it is a Non-JSON response i.e. HTML or plain text and then it is handled inside the CATCH block where I am displaying the exception directly without any processing.
function OnError(xhr, errorType, exception) {
var responseText;
$("#dialog").html("");
try {
responseText = jQuery.parseJSON(xhr.responseText);
$("#dialog").append("<div><b>" + errorType + " " + exception + "</b></div>");
$("#dialog").append("<div><u>Exception</u>:<br /><br />" + responseText.ExceptionType + "</div>");
$("#dialog").append("<div><u>StackTrace</u>:<br /><br />" + responseText.StackTrace + "</div>");
$("#dialog").append("<div><u>Message</u>:<br /><br />" + responseText.Message + "</div>");
} catch (e) {
responseText = xhr.responseText;
$("#dialog").html(responseText);
}
$("#dialog").dialog({
title: "jQuery Exception Details",
width: 700,
buttons: {
Close: function () {
$(this).dialog('close');
}
}
});
}
Demo
Downloads