ASP.NET Core 的错误页面

异常处理

Developer 环境的异常页面

ASP.NET Core App 会可以在开发阶段用UseDeveloperExceptionPage启用 Developer 异常页面:

app.UseDeveloperExceptionPage();

当遇到Unhandled 异常信息时,可以输出异常信息页面:
异常信息包括:

  • Stack trace
  • Query string parameters, if any
  • Cookies, if any
  • Headers

Production 环境的异常页面

在测试和上线阶段,可以用UseExceptionHandler 捕获异常:

var app = builder.Build();
if (!app.Environment.IsDevelopment()) //仅在开发环境输出这些详细信息
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

UseExceptionHandler 会捕获和记录异常信息,并重新执行客户端的request,所以要注意重新执行request的重入逻辑。

记录异常

可以使用 IExceptionHandlerPathFeature 获取异常的详细信息,然后写入log:

    public void OnGet()
    {
        RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;

        var exceptionHandlerPathFeature =
            HttpContext.Features.Get<IExceptionHandlerPathFeature>();

        if (exceptionHandlerPathFeature?.Error is FileNotFoundException)
        {
            ExceptionMessage = "The file was not found.";
        }

        if (exceptionHandlerPathFeature?.Path == "/")
        {
            ExceptionMessage ??= string.Empty;
            ExceptionMessage += " Page: Home.";
        }
    }

返回错误代码 UseStatusCodePages

当找不到endpoint时,会返回404。可以返回400-599的code。

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}
app.UseStatusCodePages();

UseStatusCodePages 一般不用于Production环境,因为返回的信息对于用户来说没有意义。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值