简体   繁体   中英

C# how can I access a DbEntityValidationException in my global error handler which uses getLastError method?

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM