Error Handling In .Net Core Middleware Layer

Sercan Selçuk
2 min readApr 9, 2019

Hey There..

Today we will talk about Middleware Layer that we meet with .Net Core. This layer is really important for developers, because this layer really help us about handle some important points in our project like checking authentication or handling exceptions. And with this way we write less code and can manage more things easily.

What is .Net Core Middleware ?

Middleware is a layer/structure that allows us to handle the process when a request turns into a response. This structure is assembled into an application pipeline to handle requests and responses. That means Middleware is not just for “handling exceptions”, you can control more situations. Some of them:

-Authentication
- CORS
- Health Check
- Response Caching
- Static Files
- Web Sockets

Today we will make an middleware example to handle our exceptions.

Why Do We Need Exception Handler?

If you develop a big API that exist so many controls and methods, with a global exception handler you will code just one try-catch block inside your project and you can manage all exception from that try-catch block.

Sounds cool, right?

How To Create Custom Exception Handler?

Firstly we create a class. I called it as “ExceptionMiddleware”. Then we create a constructor that contains RequestDelegate objects as parameter. That object will help up to handle request. After our constructor we should write our Invoke method which contains HttpContext. By this method every request will enter to our method.

Inside our method request gonna enter the try block and it gonna try to get a response. So if something happen wrong right one there is just one catch to see our exception. By this way every exception will in our hands.

Right now we just need to tell to startup.cs that we wrote a middleware and we gonna use it.

We open startup.cs and inside Configure void we write our code as in first line.

Here we are. Our middleware pipeline is ready to use right now. Of course, this example is a small example to check how middlewares are working in .Net Core. I hope that you like it.

--

--