This article describes how to return a desired view from an IExceptionFilter in MVC with practices. It is a part of exception handling at the filter level. Custom filters and attributes are an excellent way of injecting extra processing logic into the MVC request response pipeline. This is another most frequently asked question.
In MVC applications the user first lands on a routing module and matches the URL to best fit the route collection, this module parses the request and invokes the respected controller and action and then the controller renders the view in the browser.
Now somewhere we would like to inject some pre-processing and post-processing logic for actions and controllers. In that case we use filters. IExceptionFilter is also a part of filters.
You can also have a look at articles related to MVC here:
Result filter
This filter executes before and after the result of the action method has executed. We can use this filter if we want some modification to be done in the action's result.
- OnResultExecuting occurs just before the result is executed (before the view is rendered)
- OnResultExecuted occurs after the result is executed (after the view is rendered)
To implement the result filters we need to create a custom filter attribute class and implement the IResultFilter interface. This interface provides the two methods OnResultExecuting and OnResultExecuted.
When we execute the code we get an exception as shown in the image below:
We can handle an error using an Exception Filter.
This filter will be invoked whenever a controller or action of the controller throws an exception. This is particularly useful when we need a custom error logging module.
To implement this filter we need to create a custom filter attribute class that implements an IExceptionFilter. Here we have also set the ExceptionHandled property to let the filter know that an exception has been handled at the filter level. Kindly have a look at the image depicted below:
Here I've also added a code segment to handle an error at the OnException method level.
We can easily identify an error and related details after placing the code segment into an OnException filter. Kindly see the image shown below:
Now press F5 and see the output to understand the execution order of filters. Please see the depicted image below.
As shown in the above image we have been redirected to a Custom Error page from the action level. I hope it will help you to understand the exception handling in MVC.
I hope you enjoyed this and that it may help you down the line.
Keep coding and Smile.