filmov
tv
Global Error Handling in ASP.NET Core 8 | HOW TO - Code Samples
Показать описание
#coding #codingbootcamp #softwaredeveloper #CodeYourFuture
Exceptions are for exceptional situations. I even wrote about avoiding exceptions entirely.
But they will inevitably happen in your applications, and you need to handle them.
You can implement a global exception handling mechanism or handle only specific exceptions.
ASP.NET Core gives you a few options on how to implement this. So which one should you choose?
Today, I want to show you an old and new way to handle exceptions in ASP.NET Core 8.
Old Way: Exception Handling Midleware
The standard to implement exception handling in ASP.NET Core is using middleware. Middleware allows you to introduce logic before or after executing HTTP requests. You can easily extend this to implement exception handling. Add a try-catch statement in the middleware and return an error HTTP response.
There are 3 ways to create middleware in ASP.NET Core:
- Using request delegates
- By convention
- IMiddleware
The convention-based approach requires you to define an InvokeAsync method.
New Way: IExceptionHandler
ASP.NET Core 8 introduces a newIExceptionHandler abstraction for managing exceptions. The built-in exception handler middleware uses IExceptionHandler implementations to handle exceptions.
This interface has only one TryHandleAsync method.
TryHandleAsync attempts to handle the specified exception within the ASP.NET Core pipeline. If the exception can be handled, it should return true. If the exception can't be handled, it should return false. This allows you to implement custom exception-handling logic for different scenarios.
Lots of Great How Tos and Code Samples! Make sure to like and subscribe!