I’m developing an ASP.NET MVC 3 project and I want to implement my custom error handling logic. I’m trying to this by extending HandleErrorAttribute like this :
public class ErrorHandlingAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (!filterContext.ExceptionHandled)
{
filterContext.Result = new JsonResult {
Data = new { success = false, error = filterContext.Exception.ToString() },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
filterContext.ExceptionHandled = true;
}
}
}
What I need is, after some AJAX calls, to show some error message (by rendering a partial view) on a modal popup dialog. So, in the OnException method, I set the ExceptionContext’s result as a JsonResult (I’m not rendering the partialview to string right now, I’ll do that later)
My controller action is like below (I have decorated it with my custom filter):
[HttpPost]
[ErrorHandling]
public JsonResult Create(StopEditViewModel viewModel)
{
Stop stop = Mapper.Map<StopViewModel, Stop>(viewModel.Stop);
if (ModelState.IsValid)
{
Stop addedStop = _testFacade.AddStop(stop);
return Json(new { success = true, tableContainer = _tableName }, JsonRequestBehavior.DenyGet);
}
return Json(new { success = false }, JsonRequestBehavior.DenyGet);
}
After doing some research, I found that I need to remove filters.Add(new HandleErrorAttribute()); line from the RegisterGlobalFilters method in Global.asax. I did that too.
My web.config file has <customErrors mode="On" /> tag.
But when I call the Create POST action, if an exception occurs, the custom filter method is not invoked. The application crashes. Am I missing something?
Thanks.
you can catch Exception OnFailure method in ajax option
when you call action using Ajax it return within method.