[英]Is there a good way to handle exceptions in MVC ChildActions
I seem to be doing a lot of Exception swallowing with 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");
}
}
I feel like I'm cutting and pasting heaps of code, and with each cut an paste we all know a kitten is being drowned in angels tears. 我感觉就像是在剪切和粘贴大量代码,每次剪切粘贴,我们都知道小猫被天使的眼泪淹死了。
Is there a better way to manage exceptions in child actions that would allow the rest of the screen to render appropriately? 有没有更好的方法来管理子操作中的异常,该异常将允许屏幕的其余部分正确呈现?
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. 您可以基于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;
}
}
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.