I have an Asp.net MVC
project which is using Elmah
to log the exceptions.
The project is using Entity Framework
which can throw a DbEntityValidationException
exception where is specifies which properties couldn't be saved into Database.
I am trying to capture that exception (as is not logged in details by Elmah), and append the info to the current exception.
The problem is that, if i modify the current exception, the changes are not captured by the Elmah
. Instead, i have to raise another exception with the details about DbEntityValidationException
, but this will create two consecutive errors logs.
Is possible to append some extra text to the exception before elmah logs it?
public class ErrorHandleAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled == true)
return;
Exception exception = filterContext.Exception;
Exception dbEntityException = exception;
while (dbEntityException != null && dbEntityException is System.Data.Entity.Validation.DbEntityValidationException == false)
{
dbEntityException = dbEntityException.InnerException;
}
if (dbEntityException != null && dbEntityException is System.Data.Entity.Validation.DbEntityValidationException)
{
DbEntityValidationException dbEntityValidationException = dbEntityException as DbEntityValidationException;
StringBuilder sb = new StringBuilder();
sb.AppendLine("Db Entity Validation Exception");
foreach (var item in dbEntityValidationException.EntityValidationErrors)
{
sb.AppendFormat("Entity: {0} {1}", item.Entry.Entity.ToString(), Environment.NewLine);
foreach (var error in item.ValidationErrors)
{
sb.AppendFormat("{0}: {1} {2}", error.PropertyName, error.ErrorMessage, Environment.NewLine);
}
}
exception = new Exception(sb.ToString(), exception);
ErrorSignal.FromCurrentContext().Raise(exception);
}
}
}