我有一个返回 PartialView 的 Action:
[ChildActionOnly]
public ActionResult TabInfo(int id, string tab)
{
ViewBag.Jobid = id;
ViewBag.Tab = tab;
var viewModel = _viewModelManager.GetViewModel(tab, id);
return
PartialView(string.Format("~/Views/{0}/Index.cshtml", tab), viewModel);
}
_viewModelManager
从字典中返回一个 View 。如果用户请求一个不存在的选项卡,则会抛出 KeyNotFound
异常,但是,在我看来,我得到以下异常:
执行处理程序“System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper”的子请求时出错
@using MyApplication.UI.Helpers.Html
@model MyApplication.UI.Models.MyJobModel
@{
ViewBag.Title = "Details";
}
<p>@Model.Blah</p>
...
*@ HttpException occurs here -- renders default error view *@
@Html.Action("TabInfo", new { id = ViewBag.Jobid, tab = ViewBag.Tab })
The HandleErrorAttribute attribute on a child action method is ignored if an exception occurs in the child action itself. Therefore, a child action should handle its own exceptions. If a child action has an AuthorizeAttribute attribute applied, the attribute will execute and return an HTTP Unauthorized 401 status code.
我无法使用此 [HandleError(ExceptionType = typeof(KeyNotFoundException), View="myError")]
并且我无法使用 try/catch 进行重定向,因为重定向子操作不支持。
处理子操作异常的最佳方法是什么?
底线:我想处理异常并返回自定义错误页面。
最佳答案
如果在
GetViewModel
方法中抛出异常,那么您的 return 语句甚至不会得到处理,事实上,因为没有 catch 语句,您最终会进入global.asax 中的 Application_Error
(当然,如果有的话)。你是对的,你应该做一个
ContainsKey
检查,如果它是 false 返回你的错误页面。只是将
ContainsKey
的结果放在一个变量中,然后Assert
变量为真?或者您可以检查viewModel
变量和Assert
如果ContainsKey
为假,则确保您的错误 View 名称实际上在View 模型
。
try
catch
并不是一般意义上的好实践,如果你能避免它,你应该使用额外的逻辑(比如 ContainsKey
在这种情况下)。异常(exception)情况适用于异常(exception)情况:)。
关于c# - 如何正确处理子 Action 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10759789/