0

我似乎在使用 Child Actions 吞下很多异常。

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

我觉得我正在剪切和粘贴成堆的代码,每次剪切粘贴我们都知道一只小猫正被天使的眼泪淹没。

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

4

1 回答 1

2

You could create a CustomHandleError attribute based on Mvc's HandleError attribute, override the OnException method, do your logging and possibly return a custom view.

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;
    }
}

Then decorate any controllers and/or actions that you want to enable with this logic like so:

[ChildActionOnly]
[OutputCache(Duration = 1200, VaryByParam = "key;param")]
[CustomHandleError]
public ActionResult ChildPart(int key, string param)
{
    var model = DoRiskyExceptionProneThing(key, param)
    return View("_ChildPart", model);
}
于 2014-08-19T10:10:43.353 回答