How to return error from webmethod?
Asked Answered
P

5

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.

Peshitta answered 27/8, 2011 at 17:37 Comment(0)
N
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.

Norton answered 27/8, 2011 at 17:51 Comment(3)
So where does the Response object come from? The user's webmethod is returning a string.Uniocular
@OmegaMan: Is it not in HttpContext.Current in web methods as it otherwise is elsewhere in ASP.NET?Norton
Yes, it is contained within that global variable. WebMethods may not interact with that directly and it would be good to mention that.Uniocular
S
3

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

function onAjaxFailed(error){
     alert(error);
}
Sheepdip answered 27/8, 2011 at 17:58 Comment(1)
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.Macfarlane
M
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.

Mcgill answered 27/8, 2011 at 17:44 Comment(2)
But will this disclose page details, in exception, to the client?Marishamariska
Defines on your error page (or the framework you are using). Most often you just present a very generic error message.Mcgill
C
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);
}
Culinarian answered 17/11, 2021 at 18:0 Comment(0)
T
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; }
}

Tommy answered 6/10, 2023 at 14:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.