Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return error from webmethod?

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.

like image 925
Thomas Avatar asked Aug 27 '11 17:08

Thomas


2 Answers

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.

like image 133
David Avatar answered Nov 09 '22 09:11

David


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

function onAjaxFailed(error){
     alert(error);
}
like image 31
phnkha Avatar answered Nov 09 '22 11:11

phnkha