使用 ErrorController 而不是直接视图处理错误

发布于 2024-07-07 00:08:34 字数 174 浏览 7 评论 0原文

我正在尝试了解 MVC 中的错误处理。 我正在寻找一种集中的方式来捕获错误,记录它们,如果可能的话解决它们,如果需要采取其他操作并最终向用户显示正确的视图。

我想我可以使用 [HandleError] 过滤器来实现此目的,但我没有看到任何方法将其路由到控制器/操作。 我看到的唯一选择是将其直接指向视图。

I'm trying to get my head around the Error Handling in MVC.
What I'm looking for is a centralized way to catch errors, log them, if possible resolve them, if nessecary take other actions and finally show the correct view to the user.

I think I can use the [HandleError] filter for this, but I don't see any way to route it to a Controller/Action. The only option I see is pointing it directly to a view.

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

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

发布评论

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

评论(4

青春有你 2024-07-14 00:08:43

我正在做的(这可能是也可能不是一个好的做法)是这样的:

当发生错误时:

  • 如果我期望它并且可以处理它,我会做(用 ELMAH 记录它)
  • 如果我期望它并且无法处理它它,我将其记录到 ELMAH 并返回一个 ViewResult,这是我的错误页面
    • 包含错误描述、标准消息以及返回我正在执行的操作的链接
  • 如果我没有预料到,我在基本控制器类中重写 OnError 会执行上一步
  • 所有其他错误ELMAH 会自动记录要处理的问题,并且请求黄屏

我的大部分通用错误处理都在所有控制器的基类中。 唯一的问题是我必须在基类中手动设置控制器和操作值,以便它可以为错误页面中的重定向生成 ActionLink。

What I'm doing (which may or may not be a good practice) is this:

When an error occurs:

  • If I expected it and can handle it, I do (logging it with ELMAH)
  • If I expected it and can't handle it, I log it to ELMAH and return a ViewResult that is my error page
    • Include a description of the error, a standard message and a link back to what I was doing
  • If I didn't expect it, my override of OnError in my base controller class does the previous step
  • All other errors that can't be handled are automatically logged by ELMAH and the request yellowscreens

Most of my generic error handling goes in the base class for all my controllers. The only issue is that I have to manually set a controller and action value in the base class so that it can generate an ActionLink for the redirect in the error page.

哑剧 2024-07-14 00:08:40

为什么不创建自己的从 ActionResult 派生的 ErrorResult?

Why not create your own ErrorResult deriving from ActionResult?

云淡风轻 2024-07-14 00:08:39

Leppi,i如果您想发送到操作结果,您可以定义操作和控制器以在错误时重定向。 这是一个很好的例子,但我个人不喜欢不使用自定义页面或http代码来编码

这是我的IExtenptionFilter的例子。 我的基本控制器有一个默认的 IExceptionFilter 来处理所有不受控制的错误。

[SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes",
    Justification = "This attribute is AllowMultiple = true and users might want to override behavior.")]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class GenericExceptionHandlerFilter : ActionFilterAttribute, IExceptionFilter
{

    public Type ExceptionType { get; set;}
    public string RedirectToAction { get; set;}
    public string RedirectToController { get; set;}

    protected bool ApplyFilter(ExceptionContext filterContext)
    {
        Type lExceptionType = filterContext.Exception.GetType();
        return (ExceptionType == null ||
                lExceptionType.Equals(ExceptionType));
    }


    #region IExceptionFilter Members
    public void OnException(ExceptionContext filterContext)
    {

        if (ApplyFilter(filterContext))
        {
            IbfControllerLogger.Log(filterContext.Exception);

            filterContext.ExceptionHandled = true;

            #region Calculate Action Controller Error
            RouteValueDictionary lRoutes = new RouteValueDictionary(new
                {
                    action = RedirectToAction,
                    controller = String.IsNullOrEmpty(RedirectToController) ? (string)filterContext.RouteData.Values["controller"] : RedirectToController
                });
            UrlReWriterUtils.UrlReWriter(filterContext.Controller.ViewData, lRoutes);
            #endregion

            filterContext.Controller.TempData[TempDataName.C_TEMPDATA_EXCEPTIONERROR] = filterContext.Exception;
            filterContext.Result = new RedirectToRouteResult(lRoutes);
        }
    }
    #endregion

Leppi, iIf you want to send to Action Result, you can define Action and Controller to Redirect on Error. It's a good example, but personaly i don´t like no use custom pages or http codes to codes

Here is and example of my IExtenptionFilter. My base controler has a default IExceptionFilter to process all no controlled errors.

[SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes",
    Justification = "This attribute is AllowMultiple = true and users might want to override behavior.")]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class GenericExceptionHandlerFilter : ActionFilterAttribute, IExceptionFilter
{

    public Type ExceptionType { get; set;}
    public string RedirectToAction { get; set;}
    public string RedirectToController { get; set;}

    protected bool ApplyFilter(ExceptionContext filterContext)
    {
        Type lExceptionType = filterContext.Exception.GetType();
        return (ExceptionType == null ||
                lExceptionType.Equals(ExceptionType));
    }


    #region IExceptionFilter Members
    public void OnException(ExceptionContext filterContext)
    {

        if (ApplyFilter(filterContext))
        {
            IbfControllerLogger.Log(filterContext.Exception);

            filterContext.ExceptionHandled = true;

            #region Calculate Action Controller Error
            RouteValueDictionary lRoutes = new RouteValueDictionary(new
                {
                    action = RedirectToAction,
                    controller = String.IsNullOrEmpty(RedirectToController) ? (string)filterContext.RouteData.Values["controller"] : RedirectToController
                });
            UrlReWriterUtils.UrlReWriter(filterContext.Controller.ViewData, lRoutes);
            #endregion

            filterContext.Controller.TempData[TempDataName.C_TEMPDATA_EXCEPTIONERROR] = filterContext.Exception;
            filterContext.Result = new RedirectToRouteResult(lRoutes);
        }
    }
    #endregion
在你怀里撒娇 2024-07-14 00:08:38

MVC 附带的 HandleErrorAttribute 非常漂亮基本的 IExceptionFilter。

你有几个选择来实现我认为你想要的。

您可以在操作/控制器上使用 [HandleError (Type=typeof(MyException),View="ErrorView")] 或实现您自己的

HandleErrorAttribute 并不是很复杂。 我认为 MS 建议您复制此代码并进行修改以满足您的要求。

OnException 重写使您可以通过 ExceptionContext 访问您可能需要的所有信息 - 控制器、操作、路由数据等。

请记住设置 ExceptionHandled。 然后您可以将 filterContext.Result 设置为一个新的 RedirectToAction 实例,该实例重定向到您的 ErrorController 和操作 - 显然您可以使用属性公开特定的控制器和操作。

HandleErrorAttribute that comes with MVC is a pretty basic IExceptionFilter.

You have a few options to achieve what i think u want.

You can either use [HandleError (Type=typeof(MyException),View="ErrorView")] on actions/controllers or implement your own

HandleErrorAttribute isnt very complex. I think MS recommends you copy this code and modify to suit your requirements.

The OnException override gives you access to all that info you may need - controller, action, route data, etc - through ExceptionContext.

Remember to set the ExceptionHandled. Then you can set the filterContext.Result to a new RedirectToAction instance which redirect to your ErrorController and action - obviously you can expose the specific controller and action with properties.

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