我建立使用MVC5一個新的Web應用程序,我需要如下:MVC錯誤處理與自定義錯誤消息
- 發現錯誤
- 登錄文件的細節
- 給他們發通過電子郵件
- 添加到詳細的自定義信息(例如 記錄的
Id
我試圖閱讀) - 返回視圖自定義消息給用戶
我已經找到關於HandleErrorAttribute
但他們沒有允許具體細節添加到錯誤,也是我發現的信息說,try catch
形式給出是大量的信息服務器太重。
現在,我有:
控制器:
public partial class HomeController : Controller
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public virtual ActionResult Index()
{
try
{
return View();
}
catch (Exception e)
{
logger.Error("Error in Index: " + e);
return MVC.Error.Index("Error in Home Controller");
}
}
}
我發現這個擴展HandleErrorAttribute
似乎完成,但不這樣做我需要的一切:
private bool IsAjax(ExceptionContext filterContext)
{
return filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
}
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
{
return;
}
// if the request is AJAX return JSON else view.
if (IsAjax(filterContext))
{
//Because its a exception raised after ajax invocation
//Lets return Json
filterContext.Result = new JsonResult(){Data=filterContext.Exception.Message,
JsonRequestBehavior=JsonRequestBehavior.AllowGet};
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
}
else
{
//Normal Exception
//So let it handle by its default ways.
base.OnException(filterContext);
}
// Write error logging code here if you wish.
//if want to get different of the request
//var currentController = (string)filterContext.RouteData.Values["controller"];
//var currentActionName = (string)filterContext.RouteData.Values["action"];
}
你看過[Elmah](http://www.hanselman.com/blog/ELMAHErrorLoggingModulesAndHandlersForASPNETAndMVCToo.aspx)嗎? – 2015-02-14 00:14:06