I create example method for throw the error.
Code behind (.aspx.cs):
public partial class Test1 : System.Web.UI.Page
{
[WebMethod]
public static int Medthod1()
{
int data = 1;
try
{
data = data / (data - 1);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); // Attempted to divide by zero.
throw;
}
return 1;
}
}
I call the method by jQuery.ajax and alert the output error.
Inline Code (.aspx):
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test1</title>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(function () {
$("#button1").on("click", function (event) {
$.ajax({
type: "POST",
url: "Test1.aspx/Medthod1",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result, status, xhr) {
alert(result.d);
},
error: function (xhr, status, error) {
alert(xhr.responseText);
alert(xhr.responseText.Message);
}
});
});
});
</script>
</head>
<body>
<button type="button" id="button1">Button 1</button>
</body>
</html>
Output from the line alert(xhr.responseText);:
{"Message":"Attempted to divide by zero.","StackTrace":" at Test.Test1.Medthod1() in C:\\Project\\Test\\Test\\Test1.aspx.cs:line 29","ExceptionType":"System.DivideByZeroException"}
Output from the line alert(xhr.responseText.Message);:
undefined
However, my output expectation is only:
Attempted to divide by zero.
datavariable is 1 and 1 - 1 = 0. see the try block again.eval("(" + xhr.responseText + ")").Message;