我目前使用全局错误处理程序处理我的 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/