13luckman
13luckman

Reputation: 13

how to handle dbupdate exception in data access layer

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.

Upvotes: 1

Views: 2215

Answers (1)

James
James

Reputation: 82096

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.

Upvotes: 2

Related Questions