I need a way to distinguish between SQL exceptions using entity framework LINQ, for example how to distinguish foreing key constraint violation, or unique constraint violation when all i get from the DbUpdateException is a ton of nested inner exceptions and useless long error messages? Are there any lower level exceptions where i can do something like "Catch FKException"; catch "uniqueException" or something like that.
Using sql error codes...
catch (DbUpdateException ex)
{
var sqlex = ex.InnerException.InnerException as SqlException;
if (sqlex != null)
{
switch (sqlex.Number)
{
case 547: throw new ExNoExisteUsuario("No existe usuario destino."); //FK exception
case 2627:
case 2601:
throw new ExYaExisteConexion("Ya existe la conexion."); //primary key exception
default: throw sqlex; //otra excepcion que no controlo.
}
}
throw ex;
}
try
{
//code
}
catch (System.Data.Entity.Validation.DbEntityValidationException e)
{
string rs = "";
foreach (var eve in e.EntityValidationErrors)
{
rs = string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State);
Console.WriteLine(rs);
foreach (var ve in eve.ValidationErrors)
{
rs += "<br />" + string.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage);
}
}
throw new Exception(rs);
}