如何在无法调试时获取错误消息
本文关键字:获取 取错误 消息 调试 | 更新日期: 2024-10-19 05:20:19
我在应用程序中使用EF,它正在抛出异常
System.Data.Entity.Validation.DbEntityValidationException:一个或多个实体的验证失败。有关详细信息,请参阅"EntityValidationErrors"属性。位于Capture.Controllers.HomeController.AddFirstVisit(Int32 companyId)的System.Data.Entity.InteralContext.SaveChanges()
我可以看到我需要做些什么来了解这个错误——我需要看到EntityValidationErrors
,但问题是我无法调试——代码需要在服务器上运行,所以在本地运行不会重现这个错误。
我的问题是,在看不到对象的情况下,如何将exeception作为字符串输出?
目前,我使用catch(Exception e)
并将e.ToString()
传递给日志引擎。
如何传递错误详细信息?我希望有像这样的东西
catch(Exception e)
{
e.innerException.EntityValidationErrors; // what should this be
}
这几乎得到了答案EF Code First:我怎么看';EntityValidationErrors';属性?但我没有e.EntityValidationErrors
的选项
假设Log(string)
日志到您的日志引擎:
catch (DbEntityValidationException ex)
{
foreach (var evr in ex.EntityValidationErrors)
{
foreach (var error in evr.ValidationErrors)
{
Log(error.PropertyName + ": " + error.ErrorMessage);
}
}
}
我创建了一个类来处理模型状态错误。
public class Message
{
public string Title { get; set; }
public string Mensagem { get; set; }
public List<string> Itens { get; set; }
public string itensRetorno { get; set; }
public Message()
{
this.Itens = new List<string>();
}
public void Add(string item)
{
this.Itens.Add(item);
}
public string GetMessages()
{
var MsgItens = string.Empty;
foreach (var item in this.Itens)
{
MsgItens += "<li>" + item + "</li>";
}
this.itensRetorno = MsgItens;
return MsgItens;
}
public static class ModelStateUtils
{
public static Message GetModelStateErrors(ModelStateDictionary modelState)
{
Message msg = new Message();
List<string> errorKeys = new List<string>();
int index = 0;
foreach (var val in modelState.Values)
{
if (val.Errors.Count() > 0)
{
msg.Itens.Add(modelState.Keys.ElementAt(index));
}
index++;
}
msg.Title = "Erro";
msg.Mensagem = "Os seguintes campos são obrigatórios<br />" + msg.GetMessages();
return msg.Itens.Count() > 0 ? msg : null;
}
}
首先捕获更具体的异常:
catch(DbEntityValidationException e)
{
// Do something with e.EntityValidationErrors;
}
catch(Exception e)
{
// Do whatever you were already doing with the generic exception
}