2

我已经进行了设置,因此如果Exception抛出 an ,我可以使用我的自定义错误页面显示它。但在某些情况下,我不想被导航到错误页面,而是希望它显示一个简单的对话窗口。

public ActionResult Page1()
{
    //The custom error page shows the exception, if one was thrown

    throw new Exception( "An exception was thrown" );

    return View();
}


public ActionResult Page2()
{
    //A dialog should show the exception, if one was thrown

    try
    {
        throw new Exception( "An exception was thrown" );
    }
    catch( Exception ex )
    {
        ViewData["exception"] = ex;
    }
    return View();
}

是否可以使用 CustomAttribute 来处理在 Controller 操作中引发的异常?如果我添加CatchException到 Page2 中,我是否可以在ViewData每次抛出异常时自动将异常存储在 . 我对 CustomAttributes 没有太多经验,如果您能帮助我,我将不胜感激。

Page2 示例工作得非常好,我只是想让代码更干净,因为在每个操作(我想显示一个对话框)中都有尝试捕获并不是很漂亮。

我正在使用 .NET MVC 4。

4

2 回答 2

3

您可以创建一个基本控制器来捕获异常并为您处理它。此外,看起来控制器已经有一种机制可以为您做到这一点。您必须覆盖控制器内的 OnException 方法。你可以在这里得到一个很好的例子: Handling exception in ASP.NET MVC

此外,这里还有一个关于如何使用 OnException 的答案: Using the OnException

通过使用它,你的代码会更干净,因为你不会做很多 try/catch 块。

您必须过滤要处理的异常。像这样:

protected override void OnException(ExceptionContext contextFilter)
{
    // Here you test if the exception is what you are expecting
    if (contextFilter.Exception is YourExpectedException)
    {
        // Switch to an error view
        ...
    }
    //Also, if you want to handle the exception based on the action called, you can do this:
    string actionName = contextFilter.RouteData.Values["action"];
    //If you also want the controller name (not needed in this case, but adding for knowledge)
    string controllerName = contextFilter.RouteData.Values["controller"];
    string[] actionsToHandle = {"ActionA", "ActionB", "ActionC" };

    if (actionsTohandle.Contains(actionName)) 
    {
         //Do your handling.
    }

    //Otherwise, let the base OnException method handle it.
    base.OnException(contextFilter);
}
于 2012-10-29T18:47:38.540 回答
0

您可以创建 Exception 类的子类,并在您的 Page 2 中捕获它

internal class DialogException : Exception
{}

public ActionResult Page2()
{
    //This should a dialog if an exception was thrown

    try
    {
        //throw new Exception( "An exception was thrown, redirect" );
        throw new DialogException( "An exception was thrown, show dialog" );
    }
    catch( DialogException ex )
    {
        ViewData["exception"] = ex;
    }
    return View();
}
于 2012-10-29T18:44:04.937 回答