Applicable on Asp.Net MVC5
HandleError Filter
This belongs to Exception Filters category (Authentication Filter, Authorization Filter, Action Filter, Result Filter & Exception Filter) . This is out of the box filter provided by .Net MVC team. We can develop our customized exception filter by extending the IException interface and overriding its method, the way other customized filters are created.
By default HandleError filter redirects to "Error" view placed in Views/Shared folder. This filter can be placed on controller level as well as on Action level. Whenever exception occurred this filter redirect to Error view (by default / custom view if specified in filter).
Developer can place the error details on Error view.
Scenario: In below situation there is some exception occurred (SQL connectivity / divide by zero / Null reference exception). In this case the system redirects to Error view showing the details of error.
Below is the exception page
Now need to put below code in RegisterGlobalFilters method in App_Start/FilterConfig.cs file. This is shown below.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
{
filters.Add(new HandleErrorAttribute());
}
For above to work, need is to mention below configuration in web.config
// Put this in web.config in <system.web>
<customErrors mode="On">
</customErrors>
<customErrors mode="On">
</customErrors>
In case of error in constructor outside Actions or any other exception before controller stage in application execution pipeline. Below way will handle the error.
// Put this in web.config in <system.web>
<customErrors mode="On" defaultRedirect="~/Error/Index">
</customErrors>
<customErrors mode="On" defaultRedirect="~/Error/Index">
</customErrors>
To show customized error page based on error type, need to do below configuration
// Put this in web.config in <system.web>
<customErrors mode="On" defaultRedirect="~/Error/Index">
<error statusCode="404" redirect="~/Error/NotFound" />
</customErrors>
<customErrors mode="On" defaultRedirect="~/Error/Index">
<error statusCode="404" redirect="~/Error/NotFound" />
</customErrors>
Note: In above configurations "~/Error/Index", Here Error is controller and Index is the action.
㉺㉼㉴㉳㉽㉾㈕㈔㈆㈅㈄㈄㈃㈁㈀㉤ Ali Hamza Wadood | Software Engineer - Microsoft Technologies| LinkedIn | ㉺㉼㉴㉳㉽㉾㈕㈔㈆㈅㈄㈄㈃㈁㈀㉤