NETCORE - 全域性異常處理(Exception)
環境:.net6
建立異常中介軟體:ExceptionHandlingMiddleware.cs
using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Text.Json; using System.Threading.Tasks; namespace Rail.Medium.Middleware { public class ExceptionHandlingMiddleware { private readonly RequestDelegate _next; // 用來處理上下文請求 public ExceptionHandlingMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext httpContext) { try { await _next(httpContext); //要麼在中介軟體中處理,要麼被傳遞到下一個中介軟體中去 } catch (Exception ex) { await HandleExceptionAsync(httpContext, ex); // 捕獲異常了 在HandleExceptionAsync中處理 } } private async Task HandleExceptionAsync(HttpContext context, Exception exception) { context.Response.ContentType = "application/json"; // 返回json 型別 var response = context.Response; var errorResponse = new ErrorResponse { Success = false, }; // 自定義的異常錯誤資訊型別 switch (exception) { //case ApplicationException ex: // if (ex.Message.Contains("Invalid token")) // { // response.StatusCode = (int)HttpStatusCode.Forbidden; // errorResponse.Message = ex.Message; // break; // } // response.StatusCode = (int)HttpStatusCode.BadRequest; // errorResponse.Message = ex.Message; // break; //case KeyNotFoundException ex: // response.StatusCode = (int)HttpStatusCode.NotFound; // errorResponse.Message = ex.Message; // break; default: response.StatusCode = (int)HttpStatusCode.InternalServerError; errorResponse.Message = exception.Message;// "Internal Server errors. Check Logs!"; break; } var result = JsonSerializer.Serialize(errorResponse); await context.Response.WriteAsync(result); } private class ErrorResponse { public bool Success { get; set; } = true; public string Message { get; set; } } } }
使用中介軟體
在Program.cs 中引入中介軟體
app.UseMiddleware<ExceptionHandlingMiddleware>();
控制器中原寫法
[HttpGet] [Route("GetOrganizationSelectTreeAsync")] public async Task<ActionResult> GetOrganizationSelectTreeAsync() { try { var arr = await iUserOrganizationRepository.GetOrganizationSelectTreeAsync(); return Ok(arr); } catch (Exception ex) { return BadRequest(ex.Message); } }
增加異常處理中介軟體後
[HttpGet] [Route("GetOrganizationTreeAsync")] public async Task<ActionResult> GetOrganizationTreeAsync() { var arr = await iUserOrganizationRepository.GetOrganizationTreeAsync(); return Ok(arr); }
end