有没有一种很好的方法来处理MVC ChildActions中的异常

时间:2014-08-19 00:49:56

标签: c# asp.net-mvc child-actions

我似乎在使用Child Actions做了很多Exception。

    [ChildActionOnly]
    [OutputCache(Duration = 1200, VaryByParam = "key;param")]
    public ActionResult ChildPart(int key, string param)
    {
        try
        {
            var model = DoRiskyExceptionProneThing(key, param)
            return View("_ChildPart", model);
        }
        catch (Exception ex)
        {
            // Log to elmah using a helper method
            ErrorLog.LogError(ex, "Child Action Error ");

            // return a pretty bit of HTML to avoid a whitescreen of death on the client
            return View("_ChildActionOnlyError");
        }
    }

我觉得自己正在切割和粘贴大量代码,每次切一块糊状我们都知道一只小猫被天使淹死了。

是否有更好的方法来管理子操作中的异常,以允许屏幕的其余部分正确呈现?

1 个答案:

答案 0 :(得分:2)

您可以根据Mvc的HandleError属性创建CustomHandleError属性,覆盖OnException方法,执行日志记录并可能返回自定义视图。

public override void OnException(ExceptionContext filterContext)
{
    // Log to elmah using a helper method
    ErrorLog.LogError(filterContext.Exception, "Oh no!");

    var controllerName = (string)filterContext.RouteData.Values["controller"];
    var actionName = (string)filterContext.RouteData.Values["action"];

    if (!filterContext.HttpContext.IsCustomErrorEnabled)
    {
        filterContext.ExceptionHandled = true;
        filterContext.HttpContext.Response.Clear();
        filterContext.HttpContext.Response.StatusCode = 500;
        filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;

        var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
        filterContext.Result = new ViewResult
        {
            ViewName = "_ChildActionOnlyError",
            MasterName = Master,
            ViewData = new ViewDataDictionary(model),
            TempData = filterContext.Controller.TempData
        };
        return;
    }
}

然后使用此逻辑装饰您要启用的任何控制器和/或操作,如下所示:

[ChildActionOnly]
[OutputCache(Duration = 1200, VaryByParam = "key;param")]
[CustomHandleError]
public ActionResult ChildPart(int key, string param)
{
    var model = DoRiskyExceptionProneThing(key, param)
    return View("_ChildPart", model);
}