Question

I am working on ASP.net MVC 2.0 Application and using jqgrid in it.

I am using the following code to handle exceptions during ajax requests for loading grid

 loadError:function(xhr,status,error)
{
  alert("some thing wrong has happened"+xhr.responseTest);
}

This is showing alert when the error is raised during ajax requests.

But , here i dont want to use xhr.responseTest to show the error description , rather i am using Custom Error Handler that over rides the default HandleError attribute of MVC in the following manner:

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);                                                
                //filterContext.ExceptionHandled = true;
                //filterContext.Result = new JsonResult
                //{
                //    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                //    Data = new
                //    {
                //        error = true,
                //        message = filterContext.Exception.Message
                //    }
                //};
            }
            else
            {
                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
                };
            }
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }

        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};}
    }

I am using [CustomHandleError] filter to handle exception for the controller action.

As, one can see if the request is an ajax request , i am throwing some json response containing the error information. (Data(Error information) in the above code)

I was getting the exact error information into Data variable and setting up appropriate json error response,

But, the problem is i was not able to capture that json on client side and display that error message rather than using xhr.responseText.

I tried in the following way : but this does not work:

loadError:function(Error)
    {
      alert("some thing wrong has happened"+Error.ErrorMessage);
    }

The alert is coming as :

some thing wrong has happened+ **undefined**

it is not displaying error messsage rather displaying as Undefined which means that the json response from CustomError Handler is not recieced

Please help or give any sugesstions on how to implement above .

Was it helpful?

Solution

The callback loadError contains the same parameters like the error callback of jQuery.ajax: jqXHR of the type jqXHR (a superset of the XMLHTTPRequest object), the string textStatus and the string errorThrown. So to access to JSON response you should call $.parseJSON(jqXHR.responseText) explicitly. You can use jqXHR.getResponseHeader("Content-Type") inside of loadError to validate additionally that you try to interpret the error response from the server as JSON response only if "Content-Type" is "application/json" or "application/json; charset=utf-8". You can first verify that jqXHR.getResponseHeader("Content-Type") returns string (and not null or undefined) and then use .split(";")[0] to get "application/json" part without charset=utf-8.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top