.Net Core 全局捕获异常-中间件

1、代码版本

  .Net Core 版本 2.2

2、目录结构

  

3、定义中间件

  新建一个类 CustomerExceptionMiddleware.cs 

    /// <summary>
    /// 全局异常捕获
    /// </summary>
    public class CustomerExceptionMiddleware
    {
        private readonly RequestDelegate _next;

        public CustomerExceptionMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                context.Response.StatusCode = 500;
                context.Response.ContentType = "application/json;charset=utf-8";

                var result = new Core.Dto.APIResult<dynamic>
                {
                    Code = Core.Dto.APIResultCode.ServerError,
                    Msg = "服务器内部错误!CustomerExceptionMiddleware",
                    ErrorInfo = ex.Message
                };

                await context.Response.WriteAsync(JsonConvert.SerializeObject(result, new JsonSerializerSettings()
                {
                    //设置首字母小写
                    ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
                }));
            }
        }
    }

4、定义中间件扩展方法

    public static class MiddlewareExtension
    {
        /// <summary>
        /// 自定义全局错误捕获
        /// </summary>
        /// <param name="app"></param>
        public static void UseExceptionMiddleware(this IApplicationBuilder app)
        {
            app.UseMiddleware(typeof(CustomerExceptionMiddleware));
        }
    }

5、添加中间件

  在  Startup.cs Configure() 方法中使用

app.UseExceptionMiddleware(); //自定义全局错误捕获

  

6、效果展示

  

 

posted @ 2022-08-03 10:44  朝闲  阅读(721)  评论(0编辑  收藏  举报