0

I am trying to throw a handled exception through JQuery Post and a Webmethod so that I can get an error message back to the alert function. So this is just a test script.

I have this set up, and am catching the error, now I need to return the server error back to the alert function!

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string Test()
{
    try
    {
        string value = null;
        if (value.Length == 0) // <-- Causes exception
        {
            Console.WriteLine(value); // <-- Never reached
        }

    }

    catch (Exception E)
    {            

        StreamWriter sw = new StreamWriter(@"C:\inetpub\wwwroot\jQuery_AJAX_Database\error.txt", true);
        sw.WriteLine(E.Message);

        sw.Close();
        sw.Dispose();

        throw new Exception("error");

    }

    return "bla";

And this my Post script:

 $("#btnTest").click(function () {
            $.ajax({
                type: 'POST',
                url: "my_test2.aspx/Test",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    alert('Success!')
                },
                error: function (xhr, status, error) {
                    var exception = JSON.parse(xhr.responseText);
                    alert(exception.Message);
                    // Here I need to return server error
                }
            });
        });

Thanks P

1
  • try return new exceptionerror instead of throw new exceptionerror Commented Jun 8, 2015 at 11:49

2 Answers 2

1

You need an http status code to do that.

Modify your code into this

catch (Exception E)
    {            

        StreamWriter sw = new StreamWriter(@"C:\inetpub\wwwroot\jQuery_AJAX_Database\error.txt", true);
        sw.WriteLine(E.Message);

        sw.Close();
        sw.Dispose();

        return new HttpStatusCodeResult(500, E.Message);
    }

500 stands for internal server error. have a look for another if it fits better.

I think 400 - Bad Request might be more suited for your situation.

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

1 Comment

of what type is HttpStatusCodeResult ? where is this type found
0

Thanks @ted you got me on the right track. Solved as below!

throw new HttpException(E.Message);

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.