akkapolk
akkapolk

Reputation: 594

jQuery.ajax - Get error message (Exception.Message) which is response from code behind

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.

Upvotes: 0

Views: 2178

Answers (1)

T&#226;n
T&#226;n

Reputation: 1

The response you received was just a string. So, you need to parse it to an object before assigning.

var responseText = '{"Message":"Attempted to divide by zero.","StackTrace":"...","ExceptionType":"System.DivideByZeroException"}';

console.log(JSON.parse(responseText).Message);

// in your case, it should be:
// alert(JSON.parse(xhr.responseText).Message);

More information: JSON.parse()

Upvotes: 4

Related Questions