Asp.net Core WebApi 全局异常类
通过全局异常类,所有程序中遇到的错误都会被拦截,并友好的返回结果。
1、自定义一个全局异常处理类中间件
using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Xml.Serialization; using UFX.Mall.EntityModel; using UFX.Tools; namespace UFX.Mall.WebApi { public class ExceptionHandlerMiddleWare { private readonly RequestDelegate next; public ExceptionHandlerMiddleWare(RequestDelegate next) { this.next = next; } public async Task Invoke(HttpContext context) { try { await next(context); } catch (Exception ex) { await HandleExceptionAsync(context, ex); } } private static async Task HandleExceptionAsync(HttpContext context, Exception exception) { if (exception == null) return; await WriteExceptionAsync(context, exception).ConfigureAwait(false); } private static async Task WriteExceptionAsync(HttpContext context, Exception exception) { //记录日志 LogHelper.Error(exception.GetBaseException().ToString()); //返回友好的提示 var response = context.Response; //状态码 if (exception is UnauthorizedAccessException) response.StatusCode = (int)HttpStatusCode.Unauthorized; else if (exception is Exception) response.StatusCode = (int)HttpStatusCode.BadRequest; response.ContentType = context.Request.Headers["Accept"]; if (response.ContentType.ToLower() == "application/xml") { await response.WriteAsync(Object2XmlString(ResultMsg.Failure(exception.GetBaseException().Message))).ConfigureAwait(false); } else { response.ContentType = "application/json"; await response.WriteAsync(JsonConvert.SerializeObject(ResultMsg.Failure(exception.GetBaseException().Message))).ConfigureAwait(false); } } /// <summary> /// 对象转为Xml /// </summary> /// <param name="o"></param> /// <returns></returns> private static string Object2XmlString(object o) { StringWriter sw = new StringWriter(); try { XmlSerializer serializer = new XmlSerializer(o.GetType()); serializer.Serialize(sw, o); } catch { //Handle Exception Code } finally { sw.Dispose(); } return sw.ToString(); } } }
返回值默认格式化成自定义类ResultMsg,可根据自己的项目需求,返回自定义实体
同时会根据客户端需要的格式,自动转换为xml或者json
2、configure注册
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); //配置NLog loggerFactory.AddNLog(); env.ConfigureNLog("nlog.config"); app.UseApplicationInsightsRequestTelemetry(); app.UseApplicationInsightsExceptionTelemetry(); //异常处理中间件 app.UseMiddleware(typeof(ExceptionHandlerMiddleWare)); app.UseMvc(); ; }
3、收工,所有异常均可以处理了
分类:
.Net MVC
标签:
Asp.net Core
, 全局异常类
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架