【发布时间】:2021-06-24 19:09:52
【问题描述】:
我想在我的代码中发现异常后,将用户重定向到我自己设计的错误页面。截至目前,应用程序吃掉了异常并继续运行。
我有一个 ErrorController.cs 包含:
public class ErrorController : Controller
{
public IActionResult MyError()
{
return View();
}
}
还有一个错误页面MyError.cshtml:
@{
ViewData["Title"] = "MyError";
}
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>Development environment should not be enabled in deployed applications</strong>, as it can result in sensitive information from exceptions being displayed to end users. For local debugging, development environment can be enabled by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>, and restarting the application.
</p>
我的问题是我不知道如何让我用来查看我的应用程序的浏览器重定向到这个错误页面mysite.com/Error/MyError
据我了解,我需要向/Error/MyError 发出请求,然后控制器将打开.cshtml 页面。如果我在程序的其他地方(不是在控制器中)捕获异常,我需要这样做。
这方面的最佳做法是什么,或者老实说,有什么方法可以做到这一点?
注意:我正在寻找一个解决方案,以防引发的异常没有具有 HTTP 状态代码。抛出的异常之一是Microsoft.Data.SqlClient.SqlException
我已经看到一些关于如何使用web.config 为特定状态代码显示自定义错误页面的文档,但我认为这在这种情况下不会起作用。 (如有错误请指正)
【问题讨论】:
-
附带说明一下,我一般是编码新手,并且很乐意尽我所能澄清这个问题中任何不清楚的地方。
标签: c# asp.net-core exception