• ASP.NET Core全局异常处理


    1.使用中间件做全局异常处理,具体代码如下:

     public class CustomExceptionMiddleware
        {
            private readonly RequestDelegate _next;
            private readonly ILogger<CustomExceptionMiddleware> _logger;
    
            public CustomExceptionMiddleware(RequestDelegate next, ILogger<CustomExceptionMiddleware> logger)
            {
                _next = next;
                _logger = logger;
            }
    
            public async Task Invoke(HttpContext httpContext)
            {
                try
                {
                    await _next(httpContext);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Unhandled exception...");
                    await HandleExceptionAsync(httpContext, ex);
                }
            }
    
            private Task HandleExceptionAsync(HttpContext httpContext, Exception ex)
            {
                var result = JsonConvert.SerializeObject(new { isSuccess = false, message = ex.Message });
                httpContext.Response.ContentType = "application/json;charset=utf-8";
                return httpContext.Response.WriteAsync(result);
            }
        }
    
        // Extension method used to add the middleware to the HTTP request pipeline.
        public static class CustomExceptionMiddlewareExtensions
        {
            public static IApplicationBuilder UseCustomExceptionMiddleware(this IApplicationBuilder builder)
            {
                return builder.UseMiddleware<CustomExceptionMiddleware>();
            }
        }

    然后在Startup类的Configure方法里添加上述扩展的中间件

     public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                app.UseCustomExceptionMiddleware();
                app.UseRouting();
    
                app.UseAuthorization();
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });
            }

    2.使用过滤器做全局异常处理,具体代码如下:

     public class CustomerExceptionFilter : ExceptionFilterAttribute
        {
            private readonly ILogger<CustomerExceptionFilter> _logger;
    
            public CustomerExceptionFilter(ILogger<CustomerExceptionFilter> logger)
            {
                _logger = logger;
            }
    
            public override void OnException(ExceptionContext context)
            {
                Exception ex = context.Exception;
                HttpRequest request = context.HttpContext.Request;
                string requestUrl = $"{request.Scheme}://{request.Host.Value}{request.Path}";
                string errorMsg = $"error:{ex.GetBaseException().Message};requesturl:{requestUrl}"; 
                _logger.LogError(errorMsg);
                var result = new { code = 0, msg = errorMsg, data = "" };
                string json = JsonConvert.SerializeObject(result);
                context.HttpContext.Response.StatusCode = StatusCodes.Status200OK;
                context.HttpContext.Response.ContentType = "application/json;charset=utf-8";
                context.HttpContext.Response.WriteAsync(json);
                context.ExceptionHandled = true;
            }
        }
  • 相关阅读:
    SharePoint 2010 ——自定义上传页面与多文件上传解决方案
    SPJS Upload for SharePoint: Custom upload page for uploading documents to various document libraries in a site collection
    刚刚结束了公司EP流程,开始KMS项目开发了
    小孩出生6个月了,记录一下
    PeopleSoft FSCM Production Support 案例分析之一重大紧急事故发生时的应对策略
    PeopleSoft FSCM Production Support 案例分析
    SQL Server数据库常用的T-SQL命令
    详细讲解删除SQL Server日志的具体方法
    year()+month() 不错的Idear
    input只能输入数字
  • 原文地址:https://www.cnblogs.com/hobelee/p/16368494.html
Copyright © 2020-2023  润新知