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);
}
The _viewModelManager returns a view from a Dictionary. If a user requests a tab that does not exsist then a KeyNotFound Exception will be thrown, however, In my view 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 })
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.
I can’t user this [HandleError(ExceptionType = typeof(KeyNotFoundException), View="myError")] and I can’t redirect using a try/catch either because redirects for child actions are not supported.
What is the best way to handle child action exceptions?
Bottomline: I want to handle the exception and return a custom error page.
In case anyone else comes across this question.
I ended up using a try/catch block to catch the KeyNotFound exception. I log the error and then redirect the user to an ErrorView. In the error view I redirect the user to the appropriate view using javascript.
Error View