方法一
| app.UseExceptionHandler(configure =>{ |
| configure.Run(async context => { |
| var excHandler = context.Features.Get<IExceptionHandlerPathFeature>(); |
| var ex = excHandler.Error; |
| if(ex != null) |
| { |
| context.Response.ContentType = "text/plain;charset=utf-8"; |
| await context.Response.WriteAsync(ex.ToString()); |
| } |
| }); |
| }); |
方法二
| app.UseExceptionHandler(new ExceptionHandlerOptions(){ |
| ExceptionHandler = async context =>{ |
| var handler = context.Features.Get<IExceptionHandlerPathFeature>(); |
| var ex = handler.Error; |
| if(ex != null) |
| { |
| context.Response.ContentType = "text/plain;charset=utf-8"; |
| await context.Response.WriteAsync(ex.ToString()); |
| } |
| } |
| }); |
方法三
| app.UseExceptionHandler(new ExceptionHandlerOptions{ |
| ExceptionHandlingPath = new PathString("/error") |
| }); |
| app.Map("/error", () =>{ |
| return "error"; |
| }); |
方法四(自定义中间件)
| app.UseMiddleware<MyExceptionMiddleware>(); |
| |
| public class MyExceptionMiddleware |
| { |
| private readonly RequestDelegate _next; |
| private readonly ILogger<MyExceptionMiddleware> _logger; |
| public MyExceptionMiddleware(RequestDelegate next, ILogger<MyExceptionMiddleware> logger) |
| { |
| _logger = logger; |
| _next = next; |
| |
| } |
| public async Task InvokeAsync(HttpContext context) |
| { |
| try |
| { |
| await _next(context); |
| } |
| catch (Exception e) |
| { |
| await Handler(context,e); |
| } |
| } |
| private async Task Handler(HttpContext context,Exception exception) |
| { |
| |
| context.Response.ContentType = "application/json"; |
| var errorResponse = new ErrorResponse |
| { |
| Success = false |
| }; |
| switch (exception) |
| { |
| case ApplicationException ex: |
| { |
| break; |
| } |
| case KeyNotFoundException ex: |
| { |
| break; |
| } |
| default: |
| { |
| context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; |
| errorResponse.Message = exception.Message; |
| break; |
| } |
| } |
| _logger.LogError(exception.Message); |
| var resStr = JsonConvert.SerializeObject(errorResponse); |
| await context.Response.WriteAsync(resStr); |
| } |
| } |
| public class ErrorResponse |
| { |
| public bool Success { get; set; } = true; |
| public string Message { get; set; } |
| } |
如果程序内部的异常被捕获掉,无论是异常中间件还是异常过滤器都不能捕获到。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?