如何處理 ASP.net Core C# 中介軟體中的錯誤?
建立一個名為 CustomExceptionMiddleware 的新資料夾,並在其中建立一個 ExceptionMiddleware.cs 類。
我們首先要透過依賴注入來註冊我們的 IloggerManager 服務和 RequestDelegate。
RequestDeleagate 型別的 _next 引數是一個函式委託,可處理我們的 HTTP 請求。
在完成註冊過程後,我們需要建立 InvokeAsync() 方法。如果沒有它,RequestDelegate 無法處理請求。
_next 委託應處理請求,並且從我們的控制器獲得的 Get 操作應產生成功的響應。但是,如果請求不成功(是的,因為我們強制引發了異常),
我們的中介軟體將觸發 catch 塊並呼叫 HandleExceptionAsync 方法。
public class ExceptionMiddleware{ private readonly RequestDelegate _next; private readonly ILoggerManager _logger; public ExceptionMiddleware(RequestDelegate next, ILoggerManager logger){ _logger = logger; _next = next; } public async Task InvokeAsync(HttpContext httpContext){ try{ await _next(httpContext); } catch (Exception ex){ _logger.LogError($"Something went wrong: {ex}"); await HandleExceptionAsync(httpContext, ex); } } private Task HandleExceptionAsync(HttpContext context, Exception exception){ context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; return context.Response.WriteAsync(new ErrorDetails(){ StatusCode = context.Response.StatusCode, Message = "Internal Server Error from the custom middleware." }.ToString()); } }
為我們的 ExceptionMiddlewareExtensions 類新增另一個靜態方法 -
public static void ConfigureCustomExceptionMiddleware(this IApplicationBuilder app){ app.UseMiddleware<ExceptionMiddleware>(); }
在 Startup 類中的 Configure 方法中使用此方法 -
app.ConfigureCustomExceptionMiddleware();
廣告