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();
}