Wednesday, 4 October 2017

Global error handling in filter attribute MVC Web api

When I inherited the first skeleton iteration of the api I'm working on every action was populated with largely repeated code whose function was to capture and log errors. I centralized all this into an attribute filter class called GlobalExceptionFilterAttribute, inheriting from ExceptionFilterAttribute, that looks a bit like this:

And then applied it to all actions with this line in WebApiConfig.cs:
config.Filters.Add(new GlobalExceptionFilterAttribute());

Then, throughout the app, we can throw different types of error pretty much anywhere and this will ultimately be captured by the filter attribute. So, for instance most of my service layer methods look like this:

No comments:

Post a comment

Comments are moderated, so you'll have to wait a little bit before they appear!