In [HandleError]
you can achieve quite a lot. You can log the error. You can also figure out the kind of error and based on situation you can redirect the user to certain page.Following is one sample -
public class HandleErrorAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled)
return;
string referrerController = string.Empty;
string referrerAction = string.Empty;
if (filterContext.HttpContext.Request.UrlReferrer != null)
{
string[] segments = filterContext.HttpContext.Request.UrlReferrer.Segments;
if (segments.Length > 1)
{
referrerController = segments[1] != null ? segments[1].Replace("/", string.Empty) : string.Empty;
}
if (segments.Length > 2)
{
referrerAction = segments[2] != null ? segments[2].Replace("/", string.Empty) : string.Empty;
}
}
filterContext.Controller.TempData["exception"] = filterContext.Exception.Message;
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(
new { controller = referrerController , action = referrerAction}));
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
}
}
In this code I am saving exception message to TempData
, so that I can show the error message to user. This is just one example but you can do anything that your requirements demand. Here I am creating my own [HandleError]
attribute by inheriting from FilterAttribute
and implementing IExceptionFilter
. You can see the kind of power I am getting here. I implemented my own attribute to handle my requirements. But you can achieve the similar results by using built in [HandleError]
.
Purpose of line no. 2 is to handle a scenario where somebody else in chain has already handled the exception. Then in that case you might not be interested to handle it again. Response.Clear() is to clear the pipe before I redirect user to new page. It is not necessary to be there in your case.