From e796a4c0b2529c3bb333071c74e88bb1418e1679 Mon Sep 17 00:00:00 2001 From: Young Date: Thu, 31 Oct 2024 22:05:01 +0800 Subject: [PATCH] added exception handle middleware --- .../Extensions/ApplicationBuilderExtension.cs | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/Infrastructure/Extensions/ApplicationBuilderExtension.cs b/src/Infrastructure/Extensions/ApplicationBuilderExtension.cs index 0568098..489ca5d 100644 --- a/src/Infrastructure/Extensions/ApplicationBuilderExtension.cs +++ b/src/Infrastructure/Extensions/ApplicationBuilderExtension.cs @@ -1,12 +1,14 @@ using Asp.Versioning.ApiExplorer; using Infrastructure.Seed; using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics; +using Serilog; namespace Infrastructure.Extensions; public static class ApplicationBuilderExtension { - public static void UseDefaultSwaggerUI(this IApplicationBuilder app) + public static IApplicationBuilder UseDefaultSwaggerUI(this IApplicationBuilder app) { ArgumentNullException.ThrowIfNull(app); var apiVersionDescriptionProvider = @@ -19,5 +21,26 @@ public static class ApplicationBuilderExtension description.GroupName.ToUpperInvariant()); } }); + return app; + } + + public static IApplicationBuilder UseDefaultExceptionHandler(this IApplicationBuilder app) + { + ArgumentNullException.ThrowIfNull(app); + app.UseExceptionHandler(options => + { + options.Run(async context=> + { + context.Response.ContentType = "application/json"; + context.Response.StatusCode = StatusCodes.Status200OK; + var exceptionHandlerPathFeature = + context.Features.Get(); + var message = new MessageData(false, "unknown error", 500); + Log.Logger.Error(exceptionHandlerPathFeature?.Error.Message!); + await context.Response.WriteAsync(message.Serialize()); + }); + }); + + return app; } } \ No newline at end of file