11

When ASP.NET MVC throws an exception, it returns a 500 error with response type text/html- which, of course, is invalid JSON.

I want to respond to an Ajax request expecting JSON with an error I can receive and display to the user.

  1. Is it possible to return JSON with an HTTP status code of 500?

  2. When the problem is a missing parameter, the 500 error occurs before the controller is even called - so a controller solution might not work. For example, leaving a required parameter out in a call to an Action that normally returns a JsonResult, ASP.NET MVC sends this back to the client:

Server Error in '/' Application. The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.JsonResult EditUser(Int32, System.String, System.String, System.String, System.String, System.String, System.String, System.String, System.String)' in 'bhh'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters

I'm using jQuery; is there a better way to handle this?

1 Answer 1

11

You could use a custom error handler filter:

public class AjaxErrorHandler : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.ExceptionHandled = true;
            filterContext.Result = new JsonResult
            {
                Data = new { errorMessage = "some error message" }
            };
        }
    }
}

And then decorate your controller/actions that you are calling through Ajax or even register as global filter.

Then when performing the Ajax request you can test the presence of the error property:

$.getJSON('/foo', function(result) {
    if (result.errorMessage) {
        // Something went wrong on the server
    } else {
        // Process as normally
    }
});
Sign up to request clarification or add additional context in comments.

4 Comments

sorry but i thing that how i can parse the exact error on client side using jQuery whenever the response is invalid json. can i parse the italic using Regex
@jQuery On Planet MySQL, why would the response be invalid JSON?
i not return but ASP.NET MVC return $.trim($(data).filter(":gt(2)").text().split('\n\n')[3]) try this with return content. it parse the error
A different option would be to add the line filterContext.HttpContext.Response.StatusCode = 500; and then set an error handler on the JSON call with error: function(error) { ... }. In my view this would be a cleaner option as an error is handled by the error handler...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.