You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8 ASP.NET Core Web API自定义异常中间件无法捕获异常(已解决)

.NET 8 ASP.NET Core Web API 自定义异常中间件“未捕获异常”问题解决

开发基于.NET 8.0的ASP.NET Core Web API时,遇到自定义异常处理中间件无法捕获异常的假象:调用接口时直接定位到抛出异常的代码,提示异常未处理,程序强制终止,查阅同类问题未找到有效方案。

相关代码

Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// 使用自定义异常处理中间件
app.UseMiddleware<ExceptionHandlingMiddleware>();

// 配置HTTP请求管道
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();

ExceptionHandlingMiddleware.cs

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 Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex);
        }
    }

    private Task HandleExceptionAsync(HttpContext context, Exception ex)
    {
        Debug.WriteLine("An unhandled exception occurred:" + ex.Message);
        _logger.LogError(ex, "An unhandled exception occurred");
        context.Response.StatusCode = 500;
        return context.Response.WriteAsync("An unhandled exception occurred");
    }
}

TestController.cs

[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    [HttpGet]
    public IActionResult Test()
    {
        throw new Exception("this is a test exception message.");
    }
}

问题解决

通过断点排查确认:异常实际可以被中间件捕获,只是调试阶段被调试器拦截了。在调试版本中抛出异常时,调试器会优先触发中断,此时点击调试器的「继续」按钮,异常才会正常传递到自定义异常处理中间件中完成处理。

内容的提问来源于stack exchange,提问作者Allen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 04:05:17