zoukankan      html  css  js  c++  java
  • ASP.Net Core API 全局处理异常

    在上面的示例中,我们的 action 内部有一个 try-catch 代码块。这一点很重要,我们需要在我们的 action 方法体中处理所有的异常(包括未处理的)。一些开发者在 action 中使用 try-catch 代码块,这种方式明显没有任何问题。但我们希望 action 尽量保持简洁。因此,从我们的 action 中删除 try-catch ,并将其放在一个集中的地方会是一种更好的方式。.NET Core 给我们提供了一种处理全局异常的方式,只需要稍加修改,就可以使用内置且完善的的中间件。我们需要做的修改就是在 Startup 类中修改 Configure方法:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
       app.UseExceptionHandler(config =>
       {
           config.Run(async context =>
           {
               context.Response.StatusCode = 500;
               context.Response.ContentType = "application/json";
     
               var error = context.Features.Get<IExceptionHandlerFeature>();
               if (error != null)
               {
                   var ex = error.Error;
                   await context.Response.WriteAsync(new ErrorModel
                   {
                       StatusCode = 500,
                       ErrorMessage = ex.Message
                   }.ToString());
               }
           });
       });
     
       app.UseRouting();
     
       app.UseEndpoints(endpoints =>
       {
           endpoints.MapControllers();
       });
    }

    我们也可以通过创建自定义的中间件来实现我们的自定义异常处理:

    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
    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("Unhandled exception....", ex);
               await HandleExceptionAsync(httpContext, ex);
           }
       }
    
       private Task HandleExceptionAsync(HttpContext httpContext, Exception ex)
       {
           //todo
           return Task.CompletedTask;
       }
    }
    
    // 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>();
       }
    }

    之后,我们只需要将其注入到应用程序的请求管道中即可:

    1
    2
    3
    4
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
       app.UseCustomExceptionMiddleware();
    }
  • 相关阅读:
    代码生成器所用到的东西
    被float.parse吃掉的0.03...
    Microsoft Visual Studio 2010 Ultimate ISO 官方下载地址
    关于.net实现网站模板机制(非标签替换)
    关于ACCESS的事务与存储过程的调用
    关于如何实现左中右三栏布局, 左右固定宽度,中间随屏幕自适应
    几个台湾优秀个人博客网站
    [转]MathType常见问题
    Qt中int转换成QString
    fatal error C1189: #error : The C++ Standard Library forbids macroizing keywords. Enable warning C4005 to find the forbidden macro.
  • 原文地址:https://www.cnblogs.com/xietianjiao/p/12418515.html
Copyright © 2011-2022 走看看