2

How do I get error message from webmethod, I want to initiate error. Also, I want different error messages for different occasions.

        $.ajax({
            type: "POST",
            url: "betting.aspx/submitFunction",
            data: JSON.stringify({ results: jsonObj, edit: $("#ctl00_ContentPlaceHolder1_CreateOrEdit").val() }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(arg) { //call successfull
                window.location = "bHistory.aspx";
            },
            error: function(xhr) {
                alert("Error! You need to login, and try again");
                window.location = "login.aspx";
                //error occurred
            }
        });

2 Answers 2

5

You could try this:

error: function(msg, status) {
    if (status === "error") {
        var errorMessage = $.parseJSON(msg.responseText);
        alert(errorMessage.Message);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I've faced that problem as well. the issue is that if you throw an exception from your web method, it gets wrapped, like so "Message":"{your message}","StackTrace":" at ...

what I ended up doing was creating this js function to parse the returned exception.
it's pretty ugly, and I'd love to see if anyone's come up with anything better.

function getErrorMessage(e) {
    return e.responseText.substring(e.responseText.indexOf("\"Message\":\"") + "\"Message\":\"".length, e.responseText.indexOf("\",\"Stack"));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.