Exclude link restriction exception from SQL in C #

Which would be the right way to throw exceptions that the SQL server throws when I delete data using link restriction from C # code.
I want to show my message to users as:
  "I can’t delete the data because it’s being used"
, and not show the message as follows:

The DELETE statement conflicted with the REFERENCE constraint ... The conflict ccurred*in database "rampa", table "dbo.doc", column 'kartica_id'.
+3
source share
2 answers

Use this:

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

sql SqlException . , , SqlException.Number, SQL. .

+6

ConstraintException , , .

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
}
+2

Source: https://habr.com/ru/post/1766541/


All Articles