I want to handle the errors returned by the Entity Framework.
In this example I'm forcing the insertion of a duplicate record (Name already in the database where the column of the table is configured as a Unique Index ):
[HttpPost]
[ValidateAntiForgeryToken]
[Authorization(Roles = "Editar")]
public ActionResult Gravar(Domain.Cidade obj)
{
if (ModelState.IsValid)
{
try {
if (new App.Cidade().Gravar(obj))
return RedirectToAction("Listar");
}
catch (SqlException e) {
TempData["Mensagens"] = "Ocorreu um erro enquanto ...";
}
catch (EntitySqlException e) {
TempData["Mensagens"] = "Ocorreu um erro enquanto ...";
}
catch (EntityException e) {
TempData["Mensagens"] = "Ocorreu um erro enquanto ...";
}
catch (Exception e) {
TempData["Mensagens"] = "Ocorreu um erro enquanto ...";
}
}
return View("Cadastro", obj);
}
See what I have separated into three basic types of error handling: SqlException
, EntitySqlException
, and System.Exception
.
But the returned exception is always falling on the treatment for System.Exception
.
My save method:
public bool Gravar(Domain.Cidade obj)
{
var record = context.Cidades.SingleOrDefault(x => x.Id == obj.Id);
if (record == null)
context.Cidades.Add(obj);
else
context.Entry(record).CurrentValues.SetValues(obj);
context.SaveChanges();
return true;
}
How do I get the correct return from the Exception type?