266 UseExceptionHandler(重定向到指定路由,友好展示报错内容)

示例

新建HomeController.cs

using Microsoft.AspNetCore.Mvc;

namespace CRUDExample.Controllers
{
    public class HomeController : Controller
    {
        [Route("Error")]
        public IActionResult Error()
        {
            return View(); //Views/Shared/Error
        }
    }
}

Views/Shared下面新建Error.cshtml

@{
    ViewBag.Title = "Error";
}

<div class="text-center">
    <h1>Error</h1>
    <h2 class="text-red">Error occurred during execution</h2>
    <img src="~/error.svg" width="500px" style="margin-top:100px" />
</div>

Program.cs中else里面添加UseExceptionHandler

var app = builder.Build();

app.UseSerilogRequestLogging();

if (builder.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Error");
    app.UseExceptionHandlingMiddleware();
}

异常处理中间件ExceptionHandlingMiddleware中添加throw抛出异常,如果不抛出异常就无法定位到Error路由

public async Task Invoke(HttpContext httpContext)
{
    try
    {
        await _next(httpContext);  
    }
    catch (Exception ex)
    {
        if (ex.InnerException != null)
        {
            _logger.LogError("{ExceptionType}{ExceptionMassage}", ex.InnerException.GetType().ToString(), ex.InnerException.Message);
        }
        else
        {
            _logger.LogError("{ExceptionType}{ExceptionMassage}", ex.GetType().ToString(), ex.Message);
        }
        throw;
    }
    //httpContext.Response.StatusCode = 500;
    //await httpContext.Response.WriteAsync("Error occurred");
}

如何根据实际报错显示不同报错内容

改造HomeController

using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;

namespace CRUDExample.Controllers
{
    public class HomeController : Controller
    {
        [Route("Error")]
        public IActionResult Error()
        {
            IExceptionHandlerPathFeature? exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
            if (exceptionHandlerPathFeature != null && exceptionHandlerPathFeature.Error != null)
            {
                ViewBag.ErrorMessage = exceptionHandlerPathFeature.Error.Message;
            }
            return View(); //Views/Shared/Error
        }
    }
}

将ViewBag放到Error.cshtml视图中

@{
    ViewBag.Title = "Error";
}

<div class="text-center">
    <h1>Error</h1>
    <h2 class="text-red">@ViewBag.ErrorMessage</h2>
    <img src="~/error.svg" width="500px" style="margin-top:100px" />
</div>

程序运行后显示如下

拓展阅读

Handle errors in ASP.NET Core | Microsoft Learn

Gitee获取源码:

https://gitee.com/huang_jianhua0101/asp.-net-core-8.git

  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黄健华Yeah

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值