Here i have explained how to get Exception Message in Ajax Method using jQuery in Asp.Net C#.

Step 1) Add HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Get Exception Message in Ajax Method using jQuery in Asp.Net C#.</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function () {
$('#btnSum').click(function () {
var val1 = $.trim($('#txtVal1').val());
var val2 = $.trim($('#txtVal2').val());
$.ajax({
type: "POST",
url: "Get-Exception-Message-jQuery.aspx/GetSumofNumbers",
data: "{'val1':'" + val1 + "', 'val2':'" + val2 + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$('#lblMessage').text(response.d)
},
error: function (data) {
var r = jQuery.parseJSON(data.responseText);
var errorMessage = r.Message;
var exceptionType = r.ExceptionType;
var stackTrace = r.StackTrace;
$('#divStatus').html("<b>Error Message: </b>" + errorMessage + "</br></br>" + "<b>ExceptionType: </b>" + exceptionType + "</br></br>" + "<b>Asp.Net StackTrace: </b>" + stackTrace)
}
});
return false;
});
});  
</script>
</head>
<body>
<form id="form1" runat="server">
<h1> Get Exception Message in Ajax Method using jQuery in Asp.Net C#.</h1>
<div>
<table>
<tr><td>First Number:</td><td><input type="text" id="txtVal1" /></td></tr>
<tr><td>Second Number:</td><td><input type="text" id="txtVal2" /> </td></tr>
<tr><td>SUM:</td><td><label id="lblMessage"/></td></tr>
<tr><td colspan="2"><input type="button" id="btnSum" value="Get Sum" /></td></tr>
</table>
<hr />
<div id="divStatus"></div>
</div>
</form>
</body>
</html>

Step 2) Import Namespaces

using System;
using System.Web.Services;

Step 3) C#

 [WebMethod]
    public static int GetSumofNumbers(int val1, int val2)
    {
        return val1 + val2;
    }

Screenshot

Add Comments