.net6webapi捕获全局异常
using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Sino.Intelligence.DataAccess.IServiceAccess.ILogs; using Sino.Intelligence.DataAccess.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Text.Json; using System.Threading.Tasks; namespace Sino.Intelligence.DataAccess.CustomMiddleware { public class ExceptionHandlingMiddleware { private readonly RequestDelegate _next; // 用来处理上下文请求 //private readonly ILogger<ExceptionHandlingMiddleware> _logger; private readonly ILogUtility _logUtility; public ExceptionHandlingMiddleware(RequestDelegate next, ILogUtility logUtility) { _next = next; _logUtility = logUtility; } 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(); // 自定义的异常错误信息类型 switch (exception) { case ApplicationException ex: if (ex.Message.Contains("Invalid token")) { response.StatusCode = (int)HttpStatusCode.Forbidden; errorResponse.SetErrorMsg(ex.Message); break; } response.StatusCode = (int)HttpStatusCode.BadRequest; errorResponse.SetErrorMsg(ex.Message); break; case KeyNotFoundException ex: response.StatusCode = (int)HttpStatusCode.NotFound; errorResponse.SetErrorMsg(ex.Message); break; default: response.StatusCode = (int)HttpStatusCode.InternalServerError; //errorResponse.Message = "Internal Server errors. Check Logs!"; errorResponse.SetErrorMsg(exception.Message); break; } var result = JsonConvert.SerializeObject(errorResponse); _logUtility.Error(typeof(ExceptionHandlingMiddleware).Name, "HandleExceptionAsync", result, exception); await context.Response.WriteAsync(result); } } }
异常出口返回结构体
internal class ErrorResponse { public int Flag { get; set; } public int ErrorCode { get; set; } public string Message { get; set; } public bool IsOk => Flag == 1; public bool HasError => Flag == 0; public bool IsWaiting => Flag == 2; public ErrorResponse() { Flag = 0; ErrorCode = 0; } public void SetErrorMsg(string msg, int code = 0) { Message = msg; Flag = 0; ErrorCode = code; } }
最后一步注入中间件
app.UseMiddleware<ExceptionHandlingMiddleware>();
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!