1

I have 3 layer architecture. When user clicks on submit button. All the value gets set into business layer. Then into the business layer a datalayer function is called to insert data into database. I have a unique field in database. When I assign a non unique value to that field it throws an exception at DataLayer.

I need to know, what is the right approach to handle these cases. Should we check it in business layer, that non unique value can't proceed to DataAccess Layer or should we handle the exception from the Dataaccess layer. Please also let me know, how to handle such kind of exceptions and show a business message to user.

I various approaches like Error No

Shantanu Gupta
  • 20,688
  • 54
  • 182
  • 286

3 Answers3

0

If a unique value is to be inserted in the table then it will be good if you check the uniqueness before inserting in to the database. if its a web app. you can use JQuery, AJAX combination to to check for uniqueness first. A web service would help here or a simple web method in your .aspx.cs file will be called through Jquery using ajax. If the input is not unique then throw a user friendly message

Bhupendra
  • 111
  • 3
  • 12
-1
  • Your data layer should catch the sql exception and rethrow its custom exception for duplicate entity
  • Your business layer should catch this exception and then display a friendly error message to the user that the entry is duplicate

Edit: To detect that sql exception is for duplicate entry you can check out Entity Framework: How to properly handle exceptions that occur due to SQL constraints and Unique Key Violation in SQL Server - Is it safe to assume Error 2627?

Community
  • 1
  • 1
Muhammad Hasan Khan
  • 34,648
  • 16
  • 88
  • 131
-1

IMHO you should always relay on these exceptions. They're there exactly for that reason. If you would have to check for field's uniqueness by yourself then what would be the point of unique attribute? For the second part of your question. I think the user should not be responsible for providing any unique data. Therefore, there should be no information presented to the user that your dataaccess layer had to resolve any uniqueness conflict. Frankly speaking I cant think of any situation requiring the user to supply database wide unique value that you couldn't generate in your dataaccess layer behind the scenes. As to how to handle the exception, I think it depends on the nature of the data. I would drop the conflicting new input or merge the data if I could.

Can you say anything more about the system?

bor
  • 658
  • 7
  • 19
  • -1 You need to improve your imagination. Username is a value commonly asked from user that has to be unique in database and system can not decide itself during registration. – Muhammad Hasan Khan Sep 18 '11 at 15:43