Search code examples
asp.net-mvc-4entity-framework-5elmahelmah.mvc

How do I log EntityValidation errors using ELMAH MVC?


I've been writing an application using MVC4 and EF5.x, and using ELMAH for logging exceptions for review. We recently released the application, and as expected the ELMAH log filled up with several dozen exceptions. Great (and not)! The problem is that one of those exceptions is

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

Of course, there's no way to see the EntityValidationErrors property for more details and the stack trace wraps up to my SubmitChanges()

I know ELMAH has the capability of allowing us to raise our own exceptions, and in some way customize what gets logged and how. Unfortunately, I'm still very new to ELMAH and MVC and a Google search didn't turn up anything relevant. I did find a blog article on logging EntityValidationErrors, and the author specifically mentioned that he would post how to do so in ELMAH but that was posted in September of 2012 and I didn't see anything since then.

Any help would be greatly appreciated!


Solution

  • Probably the best thing to do in this case would be to wrap your context.SaveChanges(); call in a try...catch block and then log the individual items from the ValidationExceptions. Something like the following should get you started:

    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);
    }