使用 ASP.NET MVC、ELMAH 和自定义错误页进行正确的异常处理

发布于 2024-08-02 17:19:41 字数 653 浏览 4 评论 0原文

考虑以下情况:

有一个 ASP.NET MVC 应用程序利用 ELMAH 进行集中式异常日志记录。控制器标有 HandlerError 属性,以捕获特定类型的异常并向用户呈现视图。例如,

[HandleError(ExceptionType = typeof(ModelSpecificException), View = "Exceptions/ModelSpecific")]
public partial class HeavyController : Controller
{
  // Constructors and ActionResults are following here...
}

到目前为止,这按预期工作。我现在面临的问题是,“ModelSpecific”错误页面需要 ViewData 中的一些对象。有没有人有关于填充以下类型的 ViewPage 的 ViewData 字典的提示

System.Web.Mvc.ViewPage<HandleErrorInfo>

我想到的另一个想法是,也许控制器可以用于带有相应 ActionResults 的 ErrorHandling。但目前我不知道如何实现这一目标。

非常感谢任何帮助...

最诚挚的问候,

戈登

consider the following situation:

There is an ASP.NET MVC application which utilizes ELMAH for centralized ExceptionLogging. A Controller is marked with the HandlerError Attribute to catch a specific type of an exception and presents the user with a view. For example

[HandleError(ExceptionType = typeof(ModelSpecificException), View = "Exceptions/ModelSpecific")]
public partial class HeavyController : Controller
{
  // Constructors and ActionResults are following here...
}

This is working as expected so far. The problem I am facing right now is, that the "ModelSpecific" error page is needing some Objects within the ViewData. Does anyone has a hint on populating the ViewData Dictionary of a ViewPage of following Type

System.Web.Mvc.ViewPage<HandleErrorInfo>

Another idea which comes to my my mind is, that maybe a Controller could be used for the ErrorHandling with respective ActionResults. But currently I don't have a clue on how to accomplish that.

Any help is very appreciated...

best regards,

Gordon

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

枯叶蝶 2024-08-09 17:19:41

由于您的异常类和视图都是特定于模型的,因此您可以在异常本身中存储所需的额外数据吗?

if(badCondition)
{
    throw new ModelSpecificException("a bad thing happened", extraData);
}

在您看来,您可以通过 Server.GetLastError() 获取异常,然后将其转换为正确的类型以通过属性访问额外的数据。这可能是一种更简洁的方法,因为它将异常视为模型并使您远离 ViewData 集合。

Since both your exception class and the view are model specific, could you store the extra data you need in the exception itself?

if(badCondition)
{
    throw new ModelSpecificException("a bad thing happened", extraData);
}

In your view you can get the exception via Server.GetLastError() and then cast it to the correct type to access the extra data via properties. This might be a cleaner approach since it treats the exception as the model and keeps you out of the ViewData collection.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文