Catch fk and unique constraint exceptions

Posts   
 
    
hotchill avatar
hotchill
User
Posts: 180
Joined: 22-Jan-2007
# Posted on: 17-Aug-2007 15:18:56   

Dear all,

What is the recommended way to handle database constraints and display friendly user messages?

I am flushed to show it, but here is how I handle fk constraints:


/// <summary>
/// Removes the quota.
/// </summary>
/// <param name="quotaId">The quota id.</param>
/// <returns>True if the quota was deleted.</returns>
internal bool RemoveQuota(long quotaId) {
  using (DataAccessAdapter adapter = new DataAccessAdapter()) {
    try {
      QuotaEntity quota = new QuotaEntity(quotaId);
      return adapter.DeleteEntity(quota);
    } catch (ORMException ex) {
      if (ex.Message.Contains("FK_ProjectQuota_Quota") || ex.Message.Contains("FK_ProjectHistoricalQuota_Quota")) {
        throw new Application.UserMessageException("Unable to delete this quota because it is in use by at least one project.");
      }
      throw new Application.UserMessageException(ex.Message);
    }
  }
}

Should I first do a query to check that the entity is not in use or is there another exception strategy I can use?

With kind regards,

Tore.

Walaa avatar
Walaa
Support Team
Posts: 14995
Joined: 21-Aug-2005
# Posted on: 17-Aug-2007 16:15:26   

You can rely on the exception returned from the database, as the above code shows.

hotchill avatar
hotchill
User
Posts: 180
Joined: 22-Jan-2007
# Posted on: 17-Aug-2007 16:33:55   

Ok, but you do not feel it is ugly hard coding the name of the fk constraint and relying on llblgen to include it in the exception message for future releases?

jmeckley
User
Posts: 403
Joined: 05-Jul-2006
# Posted on: 17-Aug-2007 21:15:02   

if you want a general exception message for a sql exception, just catch the SqlException and return "A problem occured".

if you want a detailed exception message for a specific problem i would recommend checking for the missing value before continuing.

A simple scalar query returning the count, or GetDbCount() would do the trick.