1

I currently handle errors in my MVC application with a global error handler. In cases where I am getting DbEntityValidationException, I would like to be able to drill down to see the errors. I know this is possible in a catch statement, but I would like to access this data from my global error handler which uses the getLastError method. Is it possible to get these errors?

Here is my global error handler code:

protected void Application_Error()
    {
        //Global error handler
        HttpContext ctx = HttpContext.Current;

        Exception ex = ctx.Server.GetLastError();         
        ctx.Response.Clear();
        RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext;

            ViewResult viewResult = new ViewResult { ViewName = "Error" };
            viewResult.ViewBag.Error = ErrorManagement.getErrorMessage(ex); //this does the heavy listing with db and email

            string controllerName = rc.RouteData.GetRequiredString("controller");
            IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
            IController controller = factory.CreateController(rc, controllerName);
            ControllerContext cc = new ControllerContext(rc, (ControllerBase)controller);                

            viewResult.ExecuteResult(cc);
            ctx.Server.ClearError();

    }

So I am hoping I can get the error info from within this Exception object:

Exception ex = ctx.Server.GetLastError();

I realize, as per this article, Validation failed for one or more entities. See 'EntityValidationErrors' property for more details that I can write an extension method for the db.Save method but I was hoping to avoid this if possible.

Thanks! You're help is much appreciated.

Community
  • 1
  • 1
Julian Dormon
  • 1,767
  • 4
  • 32
  • 58
  • Validation errors should never reach this point. If I forget to enter a phone number in a web page I don't expect to see that in my mail box. – Gert Arnold Apr 21 '14 at 21:57

1 Answers1

4

Could you just test for the type of ex:

if(ex is DbEntityValidationException)
{
   var typedEx = ex as DbEntityValidationException
   //Now poke typedEx to get through root cause of your failure
}
Bill Gregg
  • 7,067
  • 2
  • 22
  • 39