第一步:添加异常中间件来拦截请求处理管道
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseStatusCodePagesWithReExecute("/Error/{0}");
//app.UseStatusCodePagesWithRedirects("/Error/{0}");
}
第二步:完善 ErrorController 并允许匿名访问
[AllowAnonymous]
[Route("Error")]
public IActionResult Error()
{
var exceptionHandlerPathFeature= HttpContext.Features.Get<IExceptionHandlerPathFeature>();
ViewBag.ExceptionPath = exceptionHandlerPathFeature.Path;
ViewBag.ExceptionMessage = exceptionHandlerPathFeature.Error.Message;
ViewBag.StackTrace = exceptionHandlerPathFeature.Error.StackTrace;
return View();
}
第三步:完成错误视图代码
@{
ViewBag.Title = "异常错误页面";
}
<h3>程序请求时,发生了一个内部错误,我们会反馈给开发团队,尽快解决该问题</h3>
<h5>请通过 ltm@xxx.org 与我们取得联系</h5>
<hr />
<h3>错误详情:</h3>
<div class="alert alert-danger">
<h5>异常路径:</h5>
<hr />
<p>@ViewBag.ExceptionPath</p>
</div>
<div class="alert alert-danger">
<h5>异常内容:</h5>
<hr />
<p>@ViewBag.ExceptionMessage</p>
</div>
<div class="alert alert-danger">
<h5>异常堆栈跟踪:</h5>
<hr />
<p>@ViewBag.StackTrace</p>
</div>