0

I have a WebMethod on an aspx page that I am calling in jquery, and I am trying to have it display the message of a thrown exception in a popup box, but instead of running the code under the error function, the debugger stops saying "exception unhandled by user". How can I return the error back to the client side?

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static void SubmitSections(string item)
    {
        try
        {
            throw new Exception("Hello");
        }

        catch (Exception ex)
        {
            HttpContext.Current.Response.Write(ex.Message);
            throw new Exception(ex.Message, ex.InnerException);
        }
    }

In my js file:

$.ajax({
    type: "POST",
    url: loc + "/SubmitSections",
    data: dataValue,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (Result) {
        $("#modal-submitting").modal('hide');
        document.location = nextPage;
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        $("#modal-submitting").modal('hide');
        alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
    }
});//ajax call end
KateMak
  • 1,619
  • 6
  • 26
  • 42
  • See this post as a solution on how to read the exception thrown: https://stackoverflow.com/a/70009394/2668852 – Derek Wade Nov 17 '21 at 23:09

2 Answers2

0

You should return an error, for example a Http Status Code 500, to be processed in client side as an Error.

Throwing Errors in server side are not being returned to the client side.

For WebMethod you should set the Response.StatusCode.

HttpContext.Current.Response.StatusCode = 500; 
Xavier Egea
  • 4,712
  • 3
  • 25
  • 39
  • Okay, I see. When you say return an error, do you mean return a string with the error message in it? How can I get the error: function() to execute? – KateMak Oct 02 '14 at 22:06
  • @KateMak return new HttpStatusCodeResult(errorCode, "Message"); Where errorCode could be 500 if you wish. – Xavier Egea Oct 02 '14 at 22:11
  • @KateMak I'm sorry to hear it. Have you deleted the Try/Catch? Could you edit your question and show me the Server side code? Thank you. – Xavier Egea Oct 02 '14 at 22:18
  • @KateMak For a WebMethod try this: HttpContext.Current.Response.StatusCode = 500; – Xavier Egea Oct 02 '14 at 22:24
  • Yup, gave that a try but I am still not seeing the error message I put in there. Instead my alert box looks like: Request:[object Object] Status: error Error: Internal Server Error – KateMak Oct 02 '14 at 22:25
  • @KateMak Check the accepted answer on this post, to check how to return status codes in WebMethod: http://stackoverflow.com/questions/5649852/asp-net-web-service-i-would-like-to-return-error-403-forbidden – Xavier Egea Oct 02 '14 at 22:28
  • Still cant seem to get the alert box to display the message I give it...just gives Internal Server Error :-( – KateMak Oct 02 '14 at 22:32
0

I think your problem is that you're making a JSON request from your client script, but your catch block just writes text into the response, not JSON, so the client error function does not fire.

Try using a library such as Newtonsoft.Json to convert .NET classes into JSON responses. You can then create some simple wrapper classes to represent response data, such as: -

[Serializable]
public class ResponseCustomer
{
    public int ID;
    public string CustomerName;
}

[Serializable]
public class ResponseError
{
    public int ErrorCode;
    public string ErrorMessage;
}

and in your catch block..

var json = JsonConvert.SerializeObject(new ResponseError 
                                           { 
                                              ErrorCode = 500, 
                                              ErrorMessage = "oh no !" 
                                           });
context.Response.Write(json);

By the way: throw new Exception(...) is not recommended practice because you will lose the stack trace, which doesn't help with debugging or logging. Recommended practice if you need to re-throw an exception is to just call throw; (no arguments).

sh1rts
  • 1,874
  • 1
  • 13
  • 14