A Coder's Blog
Catching and handling errors at controller level can be very useful. Sometimes we don’t want to handle some errors at application level How to: Handle Application-Level Errors.
There are different ways to handle controller-level errors in MVC. Each one of them with its own pro and cons.
For example you can use an exception filter or you can override the OnException method of the controller class. I’m going to show the latter.
I just created a new controller named “TestController”, and a new View named “Error” under the View > Test folder.
The exception thrown in the action Index will be caught by the OnExection method. In the exceptionContext object you will have all the info you need for logging the error for example.
You could also return specific views based on the type of the exception caught. For example a “NotFound” view if a custom ProductNotFoundException is thrown by the action Details(string sku) of the ProductController.
NOTE: You can’t handle controller-level errors in this way using .NET core. There isn’t a OnException method in the controller class anymore.