<p>How do you handle database exceptions in your application?<br>
Are you trying to validate data prior passing it to DB or just relying on DB schema validation logic?<br>
Do you try to recover from some kind of DB errors (e.g. timeouts)?</p>

<p>Here are some approaches:</p>

<ol>
<li>Validate data prior passing it to DB</li>
<li>Left validation to DB and handle DB exceptions properly</li>
<li>Validate on both sides</li>
<li>Validate some obvious constraints in business logic and left complex validation to DB </li>
</ol>

<p>What approach do you use? Why?</p>

<p><strong>Updates:</strong>  </p>

<p>I'm glad to see growing discussion.<br>
Let’s try to sum up community answers.  </p>

<p>Suggestions:  </p>

<ul>
<li>Validate on both sides</li>
<li>Check business logic constraints on
client side, let DB do integrity checks <a href="https://stackoverflow.com/questions/39371/database-exception-handling-best-practices#39406">from hamishmcn</a></li>
<li>Check early to avoid bothering DB <a href="https://stackoverflow.com/questions/39371/database-exception-handling-best-practices#39461">from ajmastrean</a></li>
<li>Check early to improve user experience <a href="https://stackoverflow.com/questions/39371/database-exception-handling-best-practices#39428">from Will</a></li>
<li>Keep DB interacting code in place to
simplify development <a href="https://stackoverflow.com/questions/39371/database-exception-handling-best-practices#39406">from hamishmcn</a></li>
<li>Object-relational mapping (NHibernate, Linq, etc.) can help you to deal with constrains <a href="https://stackoverflow.com/questions/39371/database-exception-handling-best-practices#39461">from ajmastrean</a></li>
<li>Client side validation is necessary for security reasons <a href="https://stackoverflow.com/questions/39371/database-exception-handling-best-practices#39487">from Seb Nilsson</a></li>
</ul>

<p>Do you have anything else to say? This is converted to Validation specific question. We are missing the core, i.e. "Database related Error best practices" which ones to handle and Which ones to Bubble up?</p>

[{'answer_id': 39406, 'author': 'hamishmcn', 'author_id': 3590, 'author_profile': 'https://Stackoverflow.com/users/3590', 'pm_score': 1, 'selected': False, 'text': '<p>In general, I try to validate data as soon as possible after it has been entered. This is so that I can give helpful messages to the user earlier than after they have clicked "submit" or the equivalent.<br>\nBy the time that it comes to making the db call I am hopefull that the data I am passing should be fairly good.<br>\nI try to keep db calls in the one file (or group of files) that share helper methods make it as easy as possible for the programmer (me or whoever else adds calls) to write to a log details about the exception, and what parameters were passed in etc  </p>\n'}, {'answer_id': 39414, 'author': 'Mark Struzinski', 'author_id': 1284, 'author_profile': 'https://Stackoverflow.com/users/1284', 'pm_score': 2, 'selected': False, 'text': "<p>I try to validate on both sides. 1 rule I always follow is never trust input from the user. Following this to it's conclusion, I will usually have some front end validation on the form/web page which will not even allow submission with improperly formed data. This is a blunt tool - meaning you can check/parse the value to make sure a date field contains a date. From there, I usually let my business logic check as to whether the data entry makes sense in context with how it was submitted. For example, does the date submitted fall into the expected range? Does the currency value submitted fall into the expected range? Finally, on the server side, Foreign Key constraints and Indexes can catch any errors that slip through, which will bubble up a DB exception as a last resort, which can be handled by the app code. I use this method because it filters out as many errors as possible before the DB call is invoked.</p>\n"}, {'answer_id': 39428, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>You want to reduce unnecessary trips to the DB, so performing validation within the application is a good practice.  Also, it allows you to handle data errors where it is most easy to recover from:  up near the UI (whether in the controller or within the UI layer for simpler apps) where the data is entered.</p>\n\n<p>There are some data errors that you can\'t check for programatically, however.  For instance, you can\'t validate data on the existance of related data without roundtripping to the db.  Data errors like these should be validated by the database through the use of relationships, triggers, etc.</p>\n\n<p>Where you deal with errors returned by database calls is an interesting one.  You could deal with them at the data layer, the business logic layer, or the UI layer.  The best practice in this instance is to let those errors bubble up to the last responsible moment before handling them.</p>\n\n<p>For example, if you have an ASP.NET MVC web application, you have three layers (from bottom to top):  Database, controller and UI (model, controller, and view).  Any errors thrown by your data layer should be allowed to bubble up into your controller.  At this level your application "knows" what the user is attempting to do, and can correctly inform the user about the error, suggesting different ways to handle it.  Attempting to recover from these errors within the data layer makes it much harder to know what\'s going on within the controller.  And, of course, placing business logic within the UI is not considered a best practice.</p>\n\n<p>TL;DR:  Validate everywhere, handle validation errors at the last responsible moment.</p>\n'}, {'answer_id': 39446, 'author': 'hamishmcn', 'author_id': 3590, 'author_profile': 'https://Stackoverflow.com/users/3590', 'pm_score': 0, 'selected': False, 'text': "<p>The sorts of apps that I was writing (I've since moved jobs) were in-house fat-client apps.<br>\nI would try to keep the business logic in the client, and do more mechanical validation on the db (ie validation that only related to the procedure's ability to run, as opposed to higher level validation).<br>\nIn short, validate where you can, and try to keep related types of validation together.</p>\n"}, {'answer_id': 39448, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>@aku:  DRY is nice, but its not always possible.  Validation is one of those places, as you will have three completely different and unrelated places where validation is not only possible but absolutely needed:  Within the UI, within the business logic, and within the database.</p>\n\n<p>Think of a web application.  You want to reduce trips to the server, so you include javascript validation of client data entry.  But you can\'t trust what the user enters, so you must perform validation within your business logic before touching the database.  And the database must have its own validation in order to prevent data corruption.  </p>\n\n<p>There\'s no clean way to unify these three different types of validation within a single component.  </p>\n\n<p>There are some attempts being made to unify cross-cutting responsibilities like validation within policy injectors like the P&amp;P group\'s <a href="http://blogs.msdn.com/tomholl/archive/2007/02/23/announcing-the-policy-injection-application-block.aspx" rel="noreferrer">Policy Injection Application Block</a> combined with their <a href="http://rds.yahoo.com/_ylt=A0geu.w0Or1ImvQAR19XNyoA;_ylu=X3oDMTBybnZlZnRlBHNlYwNzcgRwb3MDMQRjb2xvA2FjMgR2dGlkAw--/SIG=13f2oa1b9/EXP=1220447156/**http%3a//blogs.msdn.com/tomholl/archive/2006/11/27/validation-application-block-revealed.aspx" rel="noreferrer">Validation Application Block</a>, but these are still code based.  If you have validation that\'s not in code, you still have to maintain parallel logic separately...</p>\n'}, {'answer_id': 39461, 'author': 'Anthony Mastrean', 'author_id': 3619, 'author_profile': 'https://Stackoverflow.com/users/3619', 'pm_score': 2, 'selected': False, 'text': '<p>An object-relational mapping (ORM) tool, like <a href="http://www.hibernate.org/343.html" rel="nofollow noreferrer">NHibernate</a> (or better yet, <a href="http://www.castleproject.org/activerecord/index.html" rel="nofollow noreferrer">ActiveRecord</a>), can help you avoid a lot of validation by allowing the data model to be built right into your code as a proper C# class. You may avoid trips to the database as well, thanks to great caching and validation models built into the framework.</p>\n'}, {'answer_id': 39487, 'author': 'Seb Nilsson', 'author_id': 2429, 'author_profile': 'https://Stackoverflow.com/users/2429', 'pm_score': 2, 'selected': False, 'text': '<p>There is one killer-reason to validate on both the client-side and on the database-side, and that is <strong>security</strong>. Especially when you start using AJAX-stuff, hackable URLs and other things that make your site (in this case) more friendly to users <strong>and</strong> hackers.</p>\n\n<p>Validate on the client to provide a smooth experience to early tell the user to correct their input. Also validate in database, (<em>or in business logic, if this is considered a totally secure gateway to the database</em>) for security for you database.</p>\n'}]
['https://Stackoverflow.com/questions/39371', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1196/']