Hello I am new in mvc so I have a problem during the DB update. I have table in database which column is defined as a unique key that means I don't want to same data in that column but at the time of entering same data my data access layer class generates an exception called DbUpdate exception. I just want to handle this exception by sending a message "Your given data is already exists".. Please help me. Thanx in advance.
1 Answers
Generally, the idea is you want to raise a custom exception which make sense to each layer. The reason for this is because you want to keep your DAL abstract, for example, in your DAL you would catch this particular exception (DbUpdateException
) and raise your own custom exception e.g.
try
{
...
myContext.SaveChanges();
}
catch (DbUpdateException ex)
{
throw new DuplicateDataException("Data already exists");
}
Then in your business layer, if you want to further abstract you could throw a domain exception
try
{
dataStore.Save(new Entity { ... });
}
catch (DuplicateDataException ex)
{
throw new DomainException(ex.Message);
}
Then finally in your controller, pass the error to the view
[HttpPost]
public ActionResult SomeAction(SomeModel model)
{
try
{
myDomain.Save(model);
return View("Success", model);
}
catch (DomainException ex)
{
return View("Error", ex.Message);
}
}
The example is completely fictitious of course and may or may not apply to your specific code-base, however, the goal is to demonstrate how the exception will effectively "bubble-up" from your DAL layer back to your UI.
I am placing particular emphasis on using custom exceptions simply because it provides you with a nice clean abstraction.

- 80,725
- 18
- 167
- 237
-
what is "DuplicateDataException" in first statement. – 13luckman Nov 01 '13 at 11:32
-
@user2809702 A custom exception, I thought I explained this in my answer? – James Nov 01 '13 at 11:33
-
Actually whenever I am typing "DuplicateDataException" in DAL then it is showing as an error. – 13luckman Nov 01 '13 at 11:39
-
@user2809702 yes I am sure it is because `DuplicateDataException` is a **custom exception** I have made up. It doesn't exist in your code base, the point of the example was purely for illustration purposes. See [this answer](http://stackoverflow.com/questions/4791823/what-are-industry-standard-best-practices-for-implementing-custom-exceptions-in/4792169#4792169) on how to create custom exceptions. – James Nov 01 '13 at 11:54