views:

71

answers:

3

What will be proper way to catch exception which throw SQL server when I deleting data with Reference constraint from C# code.
I want to show my users message like:
"I can't delete the data because is used"
, rather than of showing message like this:

The DELETE statement conflicted with the REFERENCE constraint ... The conflict ccurred*in database "rampa", table "dbo.doc", column 'kartica_id'.
+1  A: 

I don't know about SQL server but most DBMSs clients throw an exception of a specific type (SQLCommandException for instance) which contains an error code

You should be able to catch the exception with a try catch block and check the error code property on the exception in the catch block

try
{
  // Perform your delete
}
catch (SQLCommandException e)
{
  if (e.ErrorCode == 5678)
  {
    // Friendly message handling
  }
}
vc 74
+2  A: 

You can access the ConstraintException and map its fields however you want to your own preferred error output.

using System.Data;

try
{
  // code that violates constraint
}
catch (ConstraintException exc)
{
  // build output message you wish using exc.Message and other fields,
  // return cleanly or rethrow as your own exception
}
Steve Townsend
+2  A: 

Use this:

try
{
   //Execute delete statement
}
catch (SqlException sqlEx)
{
   //Handle exception
}
finally
{
   //Close connection
}

All sql errors are thrown as SqlException and there are no specific errors. To find out what was error exactly, there is property SqlException.Number which is the same as SQL Error Code. You can find list of codes here.

Ivan Ferić
Your conclusion "there are no specific errors" is in conflict with Steve Townsend answer, thank you anyway +1 for link with error codes
adopilot
Well, ConstraintException is not actualy caught by executing SQLCommands but rather by using dataadapters - it handles SQLException and throws as ConstraintException
Ivan Ferić
@adopilot - @Ivan is correct here. How you must handle this depends on your ADO.Net usage. Different for SqlClient.
Steve Townsend