ASP.NET Core - Handling API errors smoothly
Every API needs to create a pattern to deal with errors. Everyone knows about it, and probably every back-end developer needs to implement some features to give nice feedback to front-end developers (as they want). API’s, in general, are using at least 4 different status codes: OK, BadRequest, NotFound and InternalServerError, and when it comes to asp.net core we need to format 4 ObjectResult objects to fulfill this necessity.
To centralize the client result format logic and run away from solutions If / Switch based, we can use this approach:
Create a BaseException class
You can use a default abstract exception to identify when some familiar error happened, working as a template of the error.
1 | public abstract class BaseException : Exception |
Extends Base Exception to a derived class
This way you can specify the ObjectResult in the Exception type, removing the necessity of If / Switch in the global error filter.
1 | public class BadRequestException : BaseException |
Create an HTTP Global Filter
Every type of result will be treated in the same way, which makes the error result more dynamic and extendable. You just need to create a new Type of Error derived from BaseException, returning the desirable ObjectResult and that is it, nothing more needs to change.
1 | public class HttpGlobalExceptionFilter : IExceptionFilter |
It’s a simple but evolvable structure that resolves duplication in code, cleaning the regular API solution.
More info: Github Source