MVC HandleError vs customErrors tag
So if I understand [HandleError]
correctly (see here) you have to add it to each Controller that you want to have errors handled on.
It开发者_如何转开发 seems much easier to just add the path of your error page into the web.config customErrors tag:
<customErrors mode="On" defaultRedirect="~/Error/Index" >
</customErrors>
In what situations would using [HandleError] be better than that?
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.
Any attribute can applied to all controllers globally in FilterConfig.RegisterGlobalFilters: filters.Add(new HandleErrorAttribute());
Can be done for API controllers too in the relevant method, i.e. WebApiConfig.Register.
However, if you only need to display a simple error page just use customErrors.
精彩评论