In this recipe, you will learn how to create and use exception filters at global, controller, and action levels.
ASP.NET Core MVC has a lot of advantages over earlier versions of ASP.NET MVC, such as ASP.NET MVC 5:
- No more
HandleError
attribute usable at global, controller, or action level (so, no morecustomErrors
attribute to parametrize inweb.config
) - No more
Application_Error
event inglobal.asax
- No more
OnException
method from the baseController
class to override
Of course, we could still use try
/catch
blocks, but it's considered a solution that is not developer-friendly. We can avoid this solution and get a cleaner code without it.
The solutions now are:
- Using an
Exception
filter (to handle exceptions in action methods) - Using an
Exception
middleware (to handle more generic errors at the application level)
An exception filter will handle exceptions from any action or filter...