• .NET CORE全局异常处理(自定义过滤器 ExceptionFilterAttribute、自定义中间件)


    1、自定义中间件处理异常(推荐) 参考:https://www.csframework.com/archive/1/arc-1-20211230-4180.htm
    using System.Net;
    using System.Text.Json;
    using ExceptionHandling.Models.Responses;
    
    namespace ExceptionHandling.Middlewares;
    
    public class ExceptionHandlingMiddleware
    {
        private readonly RequestDelegate _next;  // 用来处理上下文请求  
        private readonly ILogger<ExceptionHandlingMiddleware> _logger;
        public ExceptionHandlingMiddleware(RequestDelegate next,ILogger<ExceptionHandlingMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }
    
        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 = "Internal Server errors. Check Logs!";
                    break;
            }
            _logger.LogError(exception.Message);
            var result = JsonSerializer.Serialize(errorResponse);
            await context.Response.WriteAsync(result);
        }
    } 
    注入中间件:app.UseMiddleware<ExceptionHandlingMiddleware>();然后在Action或者Service中直接抛异常,就会走异常处理。
    2、使用过滤器 参考:https://blog.csdn.net/Daniel_yka/article/details/121062319
    public class CustomExceptionFilterAttribute: ExceptionFilterAttribute
    {
      private readonly ILogger<WeatherForecastController> _logger;
      public CustomExceptionFilterAttribute(ILogger<WeatherForecastController> logger)
      {
        _logger = logger;
      }
      public override void OnException(ExceptionContext context)
      {
        //判断该异常有没有处理
        if (!context.ExceptionHandled)
        {
          _logger.LogError($"Path:{context.HttpContext.Request.Path}Message:{context.Exception.Message}");
          context.Result = new JsonResult(new {Reslut = false,Msg = "发生异常,请联系管理员"});
          context.ExceptionHandled = true;
        }
      }
    }
    

    然后再在Startup下面的ConfigureServices注册这个类:services.AddControllers(o=>o.Filters.Add(typeof(CustomExceptionFilterAttribute)));
    此时当程序中有异常,便会进入该方法,我们就能在这里统一管理异常。

  • 相关阅读:
    【.Net】鼠标点击控制鼠标活动范围 ClipCursor
    【设计模式】工厂模式 Factory Pattern
    sublime text3 关闭更新提醒
    Mac下Sublime Text3激活码
    测试开发(1) -- 整数反转
    测试开发工程师面试资料(未完)
    Mojave使用pyenv安装python-zlib错误
    清理 Xcode 10
    mitmproxy
    卸载CocoaPods
  • 原文地址:https://www.cnblogs.com/xsj1989/p/16518919.html
Copyright © 2020-2023  润新知