How to handle exceptions for child actions correctly

I have an action that returns a PartialView:

[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);

}

_viewModelManagerreturns a view from the Dictionary. If the user requests a tab that is not exsist, then an KeyNotFoundException will be thrown , but in my opinion, I get the following exception:

Error executing child request for handler '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 in the child action method is ignored if an exception occurs in the child action itself. Therefore, the child action must handle its own exceptions. If the child action has an AuthorizeAttribute attribute, the attribute will execute and return the status code for unauthorized code 401.

[HandleError(ExceptionType = typeof(KeyNotFoundException), View="myError")] , try/catch, .

?

Bottomline: .

+3
3

, - .

try/catch, KeyNotFound. , ErrorView. javascript.

[ChildActionOnly]
    public ActionResult TabInfo(int id, string tab, string jobno)
    {
        try
        {
            var viewModel = _viewModelManager.GetViewModel(tab, id);

            ViewBag.Jobid = id;
            ViewBag.Tab = tab;

            return PartialView(string.Format("~/Views/{0}/Index.cshtml", tab), viewModel);
        }
        catch (Exception ex)
        {
            return View("Error");
        }

    }

@model System.Web.Mvc.HandleErrorInfo

@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript">
        window.location.href = '@Url.Content("~/400.htm")';
    </script>
</body>
</html>
0
  • GetViewModel, , , catch Application_Error global.asax( , ).

  • , ContainsKey, , , .

  • ContainsKey Assert, ? viewModel Assert, , ContainsKey , , viewModel.

A try catch , , , , (, ContainsKey ). :).

+3

ModelState ( , ), ValidationSummary . , . , . .

, - return PartialView(modelContainingPotentiallySensitiveInfo). , , , , , , , . , , , , , .

, PartialView , - cshtml, . , .

+1

All Articles