Java自学者论坛

 找回密码
 立即注册

手机号码,快捷登录

恭喜Java自学者论坛(https://www.javazxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,会员资料板块,购买链接:点击进入购买VIP会员

JAVA高级面试进阶训练营视频教程

Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程Go语言视频零基础入门到精通Java架构师3期(课件+源码)
Java开发全终端实战租房项目视频教程SpringBoot2.X入门到高级使用教程大数据培训第六期全套视频教程深度学习(CNN RNN GAN)算法原理Java亿级流量电商系统视频教程
互联网架构师视频教程年薪50万Spark2.0从入门到精通年薪50万!人工智能学习路线教程年薪50万大数据入门到精通学习路线年薪50万机器学习入门到精通教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程MySQL入门到精通教程
查看: 877|回复: 0

Asp.Net Core Web Api 全局异常中间件

[复制链接]
  • TA的每日心情
    奋斗
    2025-3-18 14:43
  • 签到天数: 805 天

    [LV.10]以坛为家III

    2053

    主题

    2111

    帖子

    73万

    积分

    管理员

    Rank: 9Rank: 9Rank: 9

    积分
    731050
    发表于 2021-5-31 16:17:43 | 显示全部楼层 |阅读模式

    中间件处理异常能够获取系统异常

    1、添加异常处理中间件AppExceptionHandlerMiddleware

      public class AppExceptionHandlerMiddleware
        {
            private readonly RequestDelegate _next;
            private AppExceptionHandlerOption _option = new AppExceptionHandlerOption();
            private readonly IDictionary<int, string> _exceptionStatusCodeDic;
            private readonly ILogger<AppExceptionHandlerMiddleware> _logger;
            public AppExceptionHandlerMiddleware(RequestDelegate next, Action<AppExceptionHandlerOption> actionOptions, ILogger<AppExceptionHandlerMiddleware> logger)
            {
                _next = next;
                _logger = logger;
                actionOptions(_option);
                _exceptionStatusCodeDic = new Dictionary<int, string>
                {
                    { 401, "未授权的请求" },
                    { 404, "找不到该页面" },
                    { 403, "访问被拒绝" },
                    { 500, "服务器发生意外的错误" }
                };
            }
    
            public async Task Invoke(HttpContext context)
            {
                Exception exception = null;
                try
                {
                    await _next(context); //调用管道执行下一个中间件
                }
                catch (AppException ex)
                {
                    context.Response.StatusCode = StatusCodes.Status200OK;
                    var apiResponse = new ApiResponse(){IsSuccess = false,Message = ex.ErrorMsg};
                    var serializerResult = JsonConvert.SerializeObject(apiResponse);
                    context.Response.ContentType = "application/json;charset=utf-8";
                    await context.Response.WriteAsync(serializerResult);
                }
                catch (Exception ex)
                {
                    context.Response.Clear();
                    context.Response.StatusCode = StatusCodes.Status500InternalServerError; //发生未捕获的异常,手动设置状态码
                    exception = ex;
                }
                finally
                {
                    if (_exceptionStatusCodeDic.ContainsKey(context.Response.StatusCode) && !context.Items.ContainsKey("ExceptionHandled")) //预处理标记
                    {
                        string errorMsg;
                        if (context.Response.StatusCode == 500 && exception != null)
                        {
                            errorMsg = $"{(exception.InnerException != null ? exception.InnerException.Message : exception.Message)}";
                            _logger.LogError(errorMsg);
                        }
                        else
                        {
                            errorMsg = _exceptionStatusCodeDic[context.Response.StatusCode];
                        }
                        exception = new Exception(errorMsg);
                    }
                    if (exception != null)
                    {
                        var handleType = _option.HandleType;
                        if (handleType == AppExceptionHandleType.Both) //根据Url关键字决定异常处理方式
                        {
                            var requestPath = context.Request.Path;
                            handleType = _option.JsonHandleUrlKeys != null && _option.JsonHandleUrlKeys.Count(
                                             k => requestPath.StartsWithSegments(k, StringComparison.CurrentCultureIgnoreCase)) > 0
                                ? AppExceptionHandleType.JsonHandle
                                : AppExceptionHandleType.PageHandle;
                        }
                        if (handleType == AppExceptionHandleType.JsonHandle)
                            await JsonHandle(context, exception);
                        else
                            await PageHandle(context, exception, _option.ErrorHandingPath);
                    }
                }
            }
    
            /// <summary>
            /// 统一格式响应类
            /// </summary>
            /// <param name="ex"></param>
            /// <returns></returns>
            private ApiResponse GetApiResponse(Exception ex)
            {
                return new ApiResponse() { IsSuccess = false, Message = ex.Message };
            }
    
            /// <summary>
            /// 处理方式:返回Json格式
            /// </summary>
            /// <param name="context"></param>
            /// <param name="ex"></param>
            /// <returns></returns>
            private async Task JsonHandle(HttpContext context, System.Exception ex)
            {
                var apiResponse = GetApiResponse(ex);
                var serializerResult = JsonConvert.SerializeObject(apiResponse);
                context.Response.ContentType = "application/json;charset=utf-8";
                await context.Response.WriteAsync(serializerResult);
            }
    
            /// <summary>
            /// 处理方式:跳转网页
            /// </summary>
            /// <param name="context"></param>
            /// <param name="ex"></param>
            /// <param name="path"></param>
            /// <returns></returns>
            private async Task PageHandle(HttpContext context, System.Exception ex, PathString path)
            {
                context.Items.Add("Exception", ex);
                var originPath = context.Request.Path;
                context.Request.Path = path;   //设置请求页面为错误跳转页面
                try
                {
                    await _next(context);
                }
                catch
                {
    
                }
                finally
                {
                    context.Request.Path = originPath;   //恢复原始请求页面
                }
            }
        }

    2、添加异常处理配置项 AppExceptionHandlerOption

     public class AppExceptionHandlerOption
        {
            public AppExceptionHandlerOption(
                AppExceptionHandleType handleType = AppExceptionHandleType.JsonHandle,
                IList<PathString> jsonHandleUrlKeys = null,
                string errorHandingPath = "")
            {
                HandleType = handleType;
                JsonHandleUrlKeys = jsonHandleUrlKeys;
                ErrorHandingPath = errorHandingPath;
            }
    
            /// <summary>
            /// 异常处理方式
            /// </summary>
            public AppExceptionHandleType HandleType { get; set; }
    
            /// <summary>
            /// Json处理方式的Url关键字
            /// <para>仅HandleType=Both时生效</para>
            /// </summary>
            public IList<PathString> JsonHandleUrlKeys { get; set; }
    
            /// <summary>
            /// 错误跳转页面
            /// </summary>
            public PathString ErrorHandingPath { get; set; }
        }

    3、错误处理方案

      /// <summary>
        /// 错误处理方式
        /// </summary>
        public enum AppExceptionHandleType
        {
            JsonHandle = 0,   //Json形式处理
            PageHandle = 1,   //跳转网页处理
            Both = 2          //根据Url关键字自动处理
        }

    4、相应结构

     public class ApiResponse
        {
            public int State => IsSuccess ? 1 : 0;
            public bool IsSuccess { get; set; }
            public string Message { get; set; }
        }

    5、扩展

      public static class AppExceptionHandlerExtensions
        {
            public static IApplicationBuilder UserAppExceptionHandler(this IApplicationBuilder app, Action<AppExceptionHandlerOption> options)
            {
                return app.UseMiddleware<AppExceptionHandlerMiddleware>(options);
            }
    
        }

     6、自定义异常类型

     public class AppException:Exception
        {
            public string ErrorMsg { get; set; }
            public AppException(string errorMsg)
            {
                ErrorMsg = errorMsg;
            }
        }

     

    哎...今天够累的,签到来了1...
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|小黑屋|Java自学者论坛 ( 声明:本站文章及资料整理自互联网,用于Java自学者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2025-4-21 08:23 , Processed in 0.060988 second(s), 29 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表