.NET CORE全局异常处理(自定义过滤器 ExceptionFilterAttribute、自定义中间件)
2022/7/25 23:25:28
本文主要是介绍.NET CORE全局异常处理(自定义过滤器 ExceptionFilterAttribute、自定义中间件),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1、自定义中间件处理异常(推荐) 参考:https://www.csframework.com/archive/1/arc-1-20211230-4180.htmusing 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 CORE全局异常处理(自定义过滤器 ExceptionFilterAttribute、自定义中间件)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-12-06使用Microsoft.Extensions.AI在.NET中生成嵌入向量
- 2024-11-18微软研究:RAG系统的四个层次提升理解与回答能力
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#