NETCORE - 全局异常处理(Exception)
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