0

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);
        }
    }
}
Catalin
  • 11,503
  • 19
  • 74
  • 147
  • If you want to avoid the double logging in ELMAH, you should be able to set ExceptionHandled to true yourself, right? – ThomasArdal Feb 17 '14 at 17:15
  • I've tried that, and if i set it to true, the exception won't propagate in the IIS pipeline anymore – Catalin Feb 18 '14 at 07:00
  • That's a good thing, right? This way you can log a custom exception with the right info and have the DB exception handled as an InnerException of your custom exception. – ThomasArdal Feb 18 '14 at 08:28

0 Answers0