Asp.net-Mvc-4

如何使用 ELMAH MVC 記錄 EntityValidation 錯誤?

  • September 13, 2016

我一直在使用 MVC4 和 EF5.x 編寫應用程序,並使用 ELMAH 記錄異常以供審查。我們最近發布了該應用程序,正如預期的那樣,ELMAH 日誌中充滿了幾十個異常。很棒(但不是)!問題是這些例外之一是

System.Data.Entity.Validation.DbEntityValidationException
Validation failed for one or more entities. 
See 'EntityValidationErrors' property for more details.

當然,無法查看 EntityValidationErrors 屬性以獲取更多詳細資訊,並且堆棧跟踪包含到我的 SubmitChanges()

我知道 ELMAH 有能力讓我們提出自己的異常,並以某種方式自定義記錄的內容和方式。不幸的是,我對 ELMAH 和 MVC 還是很陌生,Google搜尋並沒有找到任何相關的東西。我確實找到了一篇關於記錄 EntityValidationErrors 的部落格文章,作者特別提到他會在 ELMAH 中發佈如何做到這一點,但那是在 2012 年 9 月發布的,從那時起我什麼也沒看到。

任何幫助將不勝感激!

在這種情況下,最好的辦法可能是將您的context.SaveChanges();呼叫包裝在一個try...catch塊中,然後從 ValidationExceptions 中記錄各個項目。類似以下內容應該可以幫助您入門:

try
{
   context.SaveChanges();
}
catch (DbEntityValidationException ve)
{
   var error = ve.EntityValidationErrors.First().ValidationErrors.First();
   var msg = String.Format("Validation Error :: {0} - {1}", 
              error.PropertyName, error.ErrorMessage);
   var elmahException = new Exception(msg);

   Elmah.ErrorSignal.FromCurrentContext().Raise(elmahException);
}

引用自:https://stackoverflow.com/questions/15940725