Minimal API - 异常处理

81 阅读1分钟

默认

minimal api 默认处理异常,直接编写请求逻辑直接抛出异常,看看会怎样:

app.MapGet(
    "exception",
    () =>
    {
        throw new Exception("exception with no action");
    }
);
  • 调试阶段,IDE断点跳入异常位置

image.png

  • 点击继续,浏览器显示开发者异常界面,终端打印异常日志

image.png

  • 发布后,控制台打印异常日志,浏览器默认地显示500页面

image.png

自定义

为了获取异常详情,向ioc注册服务:

builder.Services.AddProblemDetails();

使用 UseExceptionHandler 定义异常路由处理 HttpContext

app.UseExceptionHandler(exceptionHandlerApp =>
    exceptionHandlerApp.Run(async context =>
    {
        // 获取服务
        var pds = context.RequestServices.GetService<IProblemDetailsService>();

        // 创建问题详情context
        var problemDetailContext = new ProblemDetailsContext() { HttpContext = context };
        
        // 如果服务为空 或 写入错误详情失败,记录一下
        if (pds == null || !await pds.TryWriteAsync(problemDetailContext))
        {
            // Fallback behavior
            await context.Response.WriteAsync("Fallback: An error occurred.");
        }
    })
);