.NET Core API -Exception Handling

Ibrahim Jaber
4 min readAug 22, 2021
Photo by Karlis Reimanis on Unsplash

When building an API, having exception handling is a must for the consistency of the application. We obviously don’t want any weird behavior unhandled.

It gets more tricky when we have a custom exception that is handled on a case-specific basis. i.e: Entity validation, not found resource, etc.

that's where having an exception middleware to handle exception types can be helpful.

Today I will walk you through building an exception handling middleware.

Prerequisites

in this demonstration, I'm assuming you have knowledge building API services in .NET Core.

Why Using an Exception Middleware?

when we send an HTTP request to an API, the API has a response containing a status code. i.e (204,200,400,500) etc.
So imagine this scenario, you have a custom-built exception and, it gets thrown accordingly. When the exception is thrown the API method won’t be able to provide a full breakdown of the exception or give an accurate Status code type. Having a middleware that can map the correct status code and provide an accurate error message description will ease troubleshooting issues if any occurs.

Application overview

for the application, I’m using .NET Core 3.1 and, there is 1 entity in my database “Person”. I have segregated the responsibilities of the application into small projects (API, Application, Infrastructure) → Onion Architecture.

What’s in each project:

  • API
    1- Controller → person controller
    2- Middleware → exception middleware
  • Application
    1-DTO → personDTO
    2-Exceptions → Exceptions classes
    3-Repositories Interfaces → base repository
    4-MappingProfile → AutoMapper profile
    5-Services → PersonServices
    6-ValidationClasses → using FLuietnValidation 3rd party service
  • Infrastructure
    1-Configurations → Entity configurations Constraints)
    2-Concrete Repository
    3-DBContext class

Custom Exception Classes

  • I have created 2 exceptions classes
    1- Exception class for model validation
    2-Exception class for a not found resource.

1- ModelNotFoundException

2- ModelNotValidException

- These exceptions will be thrown in the PersonService classes and they will be handled in the exception middleware class.

Building the exception middleware

When this class gets initialized (on every request the API receives). it will take the Request delegate. and then in the Invoke method tries to forward the response or catches the reception and forward it to ConvertException method.

  • Convert Exception method

Here, we walk into a switch statement and check for the exception types, it will assign the correct status type and serializes an error message if there is any.

Testing the API exception handling.

As you can see, I'm using Postman to test the API POST endpoint. thanks to the custom middleware, the correct status I getting retrieved and the related error messages are also displayed.

Conclusion

Photo by Kelly Sikkema on Unsplash

Middleware helps developers build applications more efficiently. It acts as the connective tissue between applications, data, and users. For organizations with multi-cloud and containerized environments, middleware can make it cost-effective to develop and run applications at scale.

Social media:
LinkedIn

Related topics

--

--

Ibrahim Jaber

Software developer | Programming and Blockchain enthusiast | If you'd like to buy me coffee: https://ko-fi.com/ibrahimjaber