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);
}
I find strange that you want display some HTML form in case of Ajax error. Ajax request uses typically
.fail()
method orerror
callback of jQuery.ajax to get error information. Inside of the callback one can decode the server response usingvar error = $.parseJSON(jqXHR.responseText);
and then display some error message likealert(error.ErrorMessage);
or more complex dialog. I suppose that main problem in your current code is because you don't setfilterContext.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"]
.