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
1

2 Answers 2

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; 
Sign up to request clarification or add additional context in comments.

7 Comments

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 return new HttpStatusCodeResult(errorCode, "Message"); Where errorCode could be 500 if you wish.
@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.
@KateMak For a WebMethod try this: HttpContext.Current.Response.StatusCode = 500;
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
|
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).

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.