A Professional ASP.NET Core API - Global Exception Handling
ASP.NET Core gives provides the ability to write middleware, which is logic inserted into the pipeline that the framework runs for every request that is received by the application. ASP.NET Core ships with core middleware components that enable things like rendering MVC pages, defining endpoint routes, and adding authentication support, and these things are configured in the application’s Startup class, where you can also add your own custom middleware components. This ability to easily configure and customize how ASP.NET Core processes requests is tremendously useful and powerful.
We will be creating exception-handling middleware to catch and handle any exceptions that are thrown during the execution of a request to our service.
So, Create a model for your error details as below
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Net; using System.Text.Json; using System.Threading.Tasks;
// ASPNETCORE_ENVIRONMENT = Development if (_env.IsDevelopment()) { var dic = new Dictionary<string, string> { ["StackTrace"] = ex.StackTrace, ["Message"] = ex.Message }; message = JsonSerializer.Serialize(dic); } else { message = "An internal server error has occurred."; } await WriteToReponseAsync(); } async Task WriteToReponseAsync() { if (context.Response.HasStarted) thrownew InvalidOperationException("The response has already started"); var exceptionResult = new ExceptionResult(message, (int)httpStatusCode, requestId); var result = JsonSerializer.Serialize(exceptionResult); context.Response.StatusCode = (int)httpStatusCode; context.Response.ContentType = "application/json"; await context.Response.WriteAsync(result); } } }
You may notice that the other middleware components all have custom extension methods to make adding them easy. Let’s add an extension method for our custom middleware too.