How to recieve and display JSON erroneous response in case of asp.net mvc Ajax in MVC 3.0 App

1.4k views Asked by At

I am using CustomErrorHandler attribute for handling errors in my asp.net mvc application. The code is as follows:

 public class CustomHandleErrorAttribute : HandleErrorAttribute    // Error handler 
    {
        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
            {
                return;
            }
            if (new HttpException(null, filterContext.Exception).GetHttpCode() != 500)
            {
                return;
            }
            if (!ExceptionType.IsInstanceOfType(filterContext.Exception))
            {
                return;
            }

            // if the request is AJAX return JSON else view.
            if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                filterContext.Result = AjaxError(filterContext.Exception.Message, filterContext);
            }
            else
            {
                filterContext.ExceptionHandled = true;
                var controllerName = (string)filterContext.RouteData.Values["controller"];
                var actionName = (string)filterContext.RouteData.Values["action"];
                var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

                filterContext.Result = new ViewResult
                {
                    ViewName = View,
                    MasterName = Master,
                    ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                    TempData = filterContext.Controller.TempData
                };
            }

        }
        protected JsonResult AjaxError(string message, ExceptionContext filterContext)
        {
            if (String.IsNullOrEmpty(message))
                message = "Something went wrong while processing your request. Please refresh the page and try again.";
            filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
            return new JsonResult { Data = new { ErrorMessage = message }, ContentEncoding = System.Text.Encoding.UTF8, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
    }
}

It has the capability to catch both the normal errors and Ajax errors.

In case of normal errors, i am building an error model and displaying the error view

But, In case of Ajax errors, i want to show the error message in the form of JSON.

I tried some thing like:

function Failed(data) {  // Onfailed call of MVC Ajax form
        alert("Sorry,An error occured while processing your request");
        alert(data.ErrorMessage);
    }

But, it is saying undefined for data.ErrorMessage instead of showing actual error message.

Please help/suggest on how to handle this.

Updated2: This is how it got solved:

 function Failed(jqXHR, textStatus, errorThrown) {
        var Error = $.parseJSON(jqXHR.responseText);
        alert("Sorry,An error occured while processing your request");
        alert(Error.ErrorMessage);
    }
2

There are 2 answers

7
Oleg On BEST ANSWER

I find strange that you want display some HTML form in case of Ajax error. Ajax request uses typically .fail() method or error callback of jQuery.ajax to get error information. Inside of the callback one can decode the server response using var error = $.parseJSON(jqXHR.responseText); and then display some error message like alert(error.ErrorMessage); or more complex dialog. I suppose that main problem in your current code is because you don't set filterContext.ExceptionHandled = true; in case of Ajax request in your code.

Small remark to your current code: I think that you can safe use IsAjaxRequest extension (in the form if (filterContext.HttpContext.Request.IsAjaxRequest()) {...}) instead of testing .Headers["X-Requested-With"].

0
anthr On

It looks like you're not forming the return statement properly. In your JsonResult action, try:

var returnObj = new { ErrorMessage = message };
return Json(returnObj, JsonRequestBehavior = JsonRequestBehavior.AllowGet);

If this doesn't solve the problem:

  • Do a console.log on the AJAX response object in your JavaScript.
  • Make sure that you are accessing the correct property name.
  • Make sure that JavaScript is recognizing your return as a valid object. If it is still in string form, you may need to do:

    var returnedObj = JSON.parse(jsonString);
    

Example

A console.log of the response from one of my webAPI controllers was producing this:

Json response

The JSON object is in string form in one of the response properties. I got the object i wanted by doing:

var returnedObj = JSON.parse(response.responseText);

A console.log of the returnedObj produced:

enter image description here