7

How does one return an error in an aspx page method decorated with WebMethod?

Sample Code

$.ajax({
    type: "POST",
    url: "./Default.aspx/GetData",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: AjaxSucceeded,
    error: AjaxFailed
});

[WebMethod]
public static string GetData()
{

}

How does one return error from a webmethod? So one can be able to use the jquery error portion to show the error detail.

5 Answers 5

10

I don't know if there's a more WebMethod-specific way of doing it, but in ASP.NET you'd generally just set the status code for your Response object. Something like this:

Response.Clear();
Response.StatusCode = 500; // or whatever code is appropriate
Response.End;

Using standard error codes is the appropriate way to notify a consuming HTTP client of an error. Before ending the response you can also Response.Write() any messages you want to send. The formats for those are much less standardized, so you can create your own. But as long as the status code accurately reflects the response then your JavaScript or any other client consuming that service will understand the error.

Sign up to request clarification or add additional context in comments.

3 Comments

So where does the Response object come from? The user's webmethod is returning a string.
@OmegaMan: Is it not in HttpContext.Current in web methods as it otherwise is elsewhere in ASP.NET?
Yes, it is contained within that global variable. WebMethods may not interact with that directly and it would be good to mention that.
3

Just throw the exception in your PageMethod and catch it in AjaxFailed. Something like that:

function onAjaxFailed(error){
     alert(error);
}

1 Comment

Throwing an exception does what OP has asked, by passing the exception details to the error function. When deployed though, unless customErrors element is set in the web.config, these just show up as generic errors (à la "Internal Server Error"), defeating the purpose of sending a useful message to the client, and catching it in the error function.
1

An error is indicated by the http status code (4xx - user request fault, 5xx - internal server fault) of the result page. I don't know asp.net, but I guess you have to throw an exception or something like that.

2 Comments

But will this disclose page details, in exception, to the client?
Defines on your error page (or the framework you are using). Most often you just present a very generic error message.
1

the JQuery xhr will return the error and stack trace in the responseText/responseJSON properties.

For Example: C#:

throw new Exception("Error message");

Javascript:

$.ajax({
    type: "POST",
    url: "./Default.aspx/GetData",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: AjaxSucceeded,
    error: AjaxFailed
});
function AjaxFailed (jqXHR, textStatus, errorThrown) {
    alert(jqXHR.responseJSON.Message);
}

Comments

0

I tried all those solutions among with other StackOverflow answers:

Nothing worked for me.

So I decided simply to catch [WebMethod] errors by myself manually. See my example:

[WebMethod]
public static WebMethodResponse GetData(string param1, string param2)
{
    try
    {
        // You business logic to get data.
        var jsonData = myBusinessService.GetData(param1, param2);
        return new WebMethodResponse { Success = jsonData };
    }
    catch (Exception exc)
    {
        if (exc is ValidationException) // Custom validation exception (like 400)
        {
            return new WebMethodResponse
            { 
                Error = "Please verify your form: " + exc.Message
            };
        }
        else // Internal server error (like 500)
        {
            var errRef = MyLogger.LogError(exc, HttpContext.Current);
            return new WebMethodResponse
            {
                Error = "An error occurred. Please contact your administrator. Error ref: " + errRef
            };
        }
    }
}

public class WebMethodResponse
{
    public string Success { get; set; }
    public string Error { get; set; }
}

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.