From 88ccaea826cf79b8cb58baeef0a204c27a7641e1 Mon Sep 17 00:00:00 2001 From: Semikolon Date: Mon, 12 Jun 2023 13:45:54 +0200 Subject: [PATCH] add ExceptionHandlingMiddleware --- .../Middleware/ExceptionHandlingMiddleware.cs | 38 +++++++++++++++++++ AB-API/Program.cs | 5 +++ 2 files changed, 43 insertions(+) create mode 100644 AB-API/Middleware/ExceptionHandlingMiddleware.cs diff --git a/AB-API/Middleware/ExceptionHandlingMiddleware.cs b/AB-API/Middleware/ExceptionHandlingMiddleware.cs new file mode 100644 index 0000000..c32fc02 --- /dev/null +++ b/AB-API/Middleware/ExceptionHandlingMiddleware.cs @@ -0,0 +1,38 @@ +using AB.Domain.Exceptions; +using System.Text.Json; + +namespace AB_API.Middleware +{ + public class ExceptionHandlingMiddleware : IMiddleware + { + public async Task InvokeAsync(HttpContext context, RequestDelegate next) + { + try + { + await next(context); + } + catch (Exception ex) + { + await HandleExceptionAsync(context, ex); + } + } + + private async Task HandleExceptionAsync(HttpContext httpContext, Exception ex) + { + httpContext.Response.ContentType = "application/json"; + + httpContext.Response.StatusCode = ex switch + { + NotFoundException => StatusCodes.Status404NotFound, + _ => StatusCodes.Status400BadRequest + }; + + var response = new + { + error = ex.Message + }; + + await httpContext.Response.WriteAsJsonAsync(response); + } + } +} diff --git a/AB-API/Program.cs b/AB-API/Program.cs index 056cbc9..6b2922c 100644 --- a/AB-API/Program.cs +++ b/AB-API/Program.cs @@ -3,6 +3,7 @@ using AB.Persistence; using AB.Persistence.Repos; using AB.Services; using AB.Services.Abstractions; +using AB_API.Middleware; using Microsoft.EntityFrameworkCore; using Microsoft.OpenApi.Models; using System.Text.Json.Serialization; @@ -31,6 +32,8 @@ builder.Services.AddDbContextPool(builder => builder.UseInMemoryDatabase("test"); }); +builder.Services.AddTransient(); + var app = builder.Build(); // Configure the HTTP request pipeline. @@ -40,6 +43,8 @@ if (app.Environment.IsDevelopment()) app.UseSwaggerUI(); } +app.UseMiddleware(); + app.UseHttpsRedirection(); app.UseAuthorization();