我已设置好,如果抛出Exception
,我可以使用自定义错误页面显示它。但在某些情况下,我不想导航到错误页面,但希望它显示一个简单的对话窗口。
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.
答案 0 :(得分: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);
}
答案 1 :(得分:0)
您可以创建Exception类的子类,并在您的
中捕获它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();
}