5

I want to display in a webpage an exception message raised in my .NET code in the error part of an ajax request:

[HttpPost]
[AllowAnonymous]
public virtual ActionResult AuthenticateUser(string somedata)
{
    throw new Exception("Ooops!!");
}

JS code:

        jQuery(document).ready(function () {
            jQuery.ajax(
                '@Url.Action("AuthenticateUser")',
            {
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: {
                    somedata:somedata
                },
                success: function (result) {
                    if (result == 'true') {
                        window.location = '@Url.Content(Request["returnUrl"])';
                    }
                },
                error: function (response) {
                    var responseJson = jQuery.parseJSON(response.responseText);
                    $('#errorMessage').text(responseJson.Message);

                    $('#progress_message').text("");
                },
                type: 'post'
            }
            );
        });

The error I get in "response" is HTML code and I want to parse it to get the exception message I throw from the server side. So, the better approach I came up with was to return a Json response, but despite specifying "json" as datatype I still receive HTML code in "response", so... what am I doing wrong? Is the problem the "Exception" object I throw from the server side?

2
  • Your code indicates your are redirecting in the success call back so what on earth is the point of using ajax to post. Just make a normal submit Commented May 19, 2015 at 1:57
  • Forget about the code intention, I skimmed some parts of it... So it may seem a little bit strange :) Commented May 19, 2015 at 2:07

2 Answers 2

1

The problem is that whenever an exception is thrown in a controller, it will always trigger asp.net's error page and return whatever is configured for the 500 http status code (the default result is the "yellow page of death" which is an html), what you are trying to do is custom error handling and there are several ways of doing it in depth explanation is present in this blog

One way you could do this is by overriding the OnException method:

protected override void OnException(ExceptionContext filterContext)
{
    filterContext.Result = Json(new {Message = filterContext.Exception.Message});
    filterContext.ExceptionHandled = true;
}

This will replace the default result for an internal server error (500) with a json result containing the error message, which can be obtained like below

jQuery.ajax(
            '@Url.Action("AuthenticateUser")',
        {
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (result) {
                console.log(result);
            },
            error: function (response) {
                var responseJson = jQuery.parseJSON(response.responseText);
                console.log(responseJson.Message); //Logs the exception message
            },
            type: 'post'
        });

This will catch errors Controller wise, if you want to do this application wise you will have to go a little deeper on the blog's methods (probably with the "HandleError" Attribute)

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

2 Comments

This doesn't work, the OnException handles the exception as expected, but no result is returned and the ajax "error" callback is not called.
It worked for me, I think my web.config contains something else that enables this (maybe <customerrors mode="on">), I'll check again when I can but this code is tested
0

In the end I returned JsonResults and handled the message from the view:

Server code:

[HttpPost]
[AllowAnonymous]
public virtual JsonResult AuthenticateUser(string somedata)
{
    if (ok)
       return new JsonResult() {Data="ok"}
    return new JsonResult() {Data= "Missing data blah"}
}

And in javascript:

success: function (result) {
    if (result == 'ok') {
       window.location = '@Url.Content(Request["returnUrl"])';
       return;
    }

    $('#progress_message').text("");
    $('#errorMessage').text(result);
},

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.