.net core UseExceptionHandler

 1 public static IApplicationBuilder UseCustomExceptionHandler(this IApplicationBuilder app)
 2 {
 3     app.UseExceptionHandler(configure =>
 4     {
 5         configure.Run(async handler =>
 6         {                    
 7             var response = handler.Response;
 8             var feature = handler.Features.Get<IExceptionHandlerPathFeature>();
 9             if (feature?.Error is BaseException)
10             {
11                 var error = (BaseException)feature.Error;
12                 response.StatusCode = error.StatusCode;
13                 response.ContentType = "application/json; charset=utf-8";
14                 await response.Body.WriteAsync(Encoding.UTF8.GetBytes(error.ToString()));
15             }
16 
17         });
18     });
19 
20     app.UseHsts();
21 
22     return app;
23 }

 

posted on 2020-09-15 11:38  BadTree  阅读(769)  评论(0编辑  收藏  举报