C# 如何在使用 getLastError 方法的全局错误处理程序中访问 DbEntityValidationException?

标签 c# error-handling entity-framework-5

我目前使用全局错误处理程序处理我的 MVC 应用程序中的错误。在出现 DbEntityValidationException 的情况下,我希望能够向下钻取以查看错误。我知道这在 catch 语句中是可能的,但我想从使用 getLastError 方法的全局错误处理程序访问此数据。是否有可能出现这些错误?

这是我的全局错误处理程序代码:

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

    }

所以我希望我可以从这个异常对象中获取错误信息:

异常 ex = ctx.Server.GetLastError();

我意识到,根据这篇文章,Validation failed for one or more entities. See 'EntityValidationErrors' property for more details我可以为 db.Save 方法编写一个扩展方法,但我希望尽可能避免这种情况。

谢谢!非常感谢您的帮助。

最佳答案

你能不能只测试 ex 的类型:

if(ex is DbEntityValidationException)
{
   var typedEx = ex as DbEntityValidationException
   //Now poke typedEx to get through root cause of your failure
}

关于C# 如何在使用 getLastError 方法的全局错误处理程序中访问 DbEntityValidationException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23186956/

相关文章:

c# - 时间表 : Retrieve data using SQL, LINQ 或类?

javascript - 如何捕获所有 Iframe 中的 JavaScript 错误(使用 window.error)?

php - 403 禁止 : You don't have permission to access

c# - Entity Framework 5 如何在存在关系时执行创建/更新

linq - 带有 LINQ 的 Entity Framework 在 WHERE 子句中使用 CONTAINS 对于大整数列表非常慢

c# - 防止 Entity Framework 5 查询 Information_Schema_Tables

c# - 当我尝试使用 Cake 构建我的项目时出现错误

c# - DirectoryServices.Protocols.SearchRequest 返回 GUID 的多个结果

c# - 用于查找具有非法字符的属性的 XPath

angular - 使用URL访问时出现 Angular 错误500