c# - 如何正确处理子 Action 异常

标签 c# asp.net-mvc asp.net-mvc-3 razor error-handling

我有一个返回 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 }) 

According to MS...

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 进行重定向,因为重定向子操作不支持。

处理子操作异常的最佳方法是什么?

底线:我想处理异常并返回自定义错误页面。

最佳答案

  1. 如果在 GetViewModel 方法中抛出异常,那么您的 return 语句甚至不会得到处理,事实上,因为没有 catch 语句,您最终会进入 global.asax 中的 Application_Error(当然,如果有的话)。

  2. 你是对的,你应该做一个 ContainsKey 检查,如果它是 false 返回你的错误页面。

  3. 只是将 ContainsKey 的结果放在一个变量中,然后 Assert 变量为真?或者您可以检查 viewModel 变量和 Assert 如果 ContainsKey 为假,则确保您的错误 View 名称实际上在 View 模型

try catch 并不是一般意义上的好实践,如果你能避免它,你应该使用额外的逻辑(比如 ContainsKey 在这种情况下)。异常(exception)情况适用于异常(exception)情况:)。

关于c# - 如何正确处理子 Action 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10759789/

相关文章:

c# - 安装 Windows 10 Fall Creators Update 后无法运行任何 ASP.net MVC 应用程序

asp.net - Paypal 返回网址

asp.net-mvc - 无法使DropDownListFor在MVC3中的EditorFor上工作

ASP.NET MVC3 HttpStatusCodeResult StatusDescription - 指定的参数超出有效值范围

c# - Entity Framework 不更新由触发器修改的值

c# - 如何使用接口(interface)使 MainPage.xaml.cs 与 MainActivity.cs 对话

c# - .Net 控制台应用程序作为 CLI 命令

c# - particleSystem.startSize 与 particleSystem.main.startSize

asp.net-mvc - 何时在 ASP.Net MVC 中使用 TempData 与 Session

asp.net-mvc - 如何避免在 MVC4 中使用 ViewBag 在 Controller 和 View 之间传递查询值