4

I'm working on an asp.net app. Is there a way, when catching a SqlException, to know which constraint was violated?

Benjamin Gale
  • 12,977
  • 6
  • 62
  • 100
DJPB
  • 5,429
  • 8
  • 30
  • 44
  • yep. I just want to know if the user is violating, say, a unique constraint, so the app can inform which inserted data is wrong – DJPB Mar 25 '10 at 16:07

5 Answers5

8

SqlException has a collection of SqlError objects: Errors. The SqlError have properties for error Number and you can compare this with the known constraint violation error numbers (eg. 2627).

While is true that SqlException itself exposes a Number property, it is not accurate if multiple errors happen in a single batch and hence is better to inspect the Errors collection.

Remus Rusanu
  • 288,378
  • 40
  • 442
  • 569
4
catch (SqlException ex)
{
    if (ex.Errors.Count > 0) // Assume the interesting stuff is in the first error
    {
        switch (ex.Errors[0].Number)
        {
            case 547: // Foreign Key violation
                throw new InvalidOperationException("Your FK user-friendly description", ex);
                    break;
            // other cases
        }
    }
}
2

You have to add exception handler for the ConstraintException if I understand your question correctly

try
{

}
catch(ConstraintException exc)
{
//exc.Message 
}
EgorBo
  • 6,120
  • 3
  • 35
  • 40
0

Are you letting the exception bubble up? If you don't catch it and turn custom errors off in the web.config i believe it will display it in your browser. If you are catching it i would put a break point in the catch section and inspect the exception there.

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
-1

The best thing is to catch this catch exception in your C# code behind.

catch(SqlException ex)
{
    if (ex.Message.Contains("UniqueConstraint"))
        throw new UniqueConstraintException();

    throw;
} 

You can create your own exception and throw that from your data layer, otherwise you can directly catch the exception as mentioned above.

using System; 

public class UniqueConstraintException : Exception
{
} 
Benjamin Gale
  • 12,977
  • 6
  • 62
  • 100
Maddy
  • 7
  • 1
  • -1 for `UniqueConstraintException : Exception` (bypassing SqlException). Also because there is `ConstraintException` in .NET framework already. – Victor Zakharov Nov 03 '14 at 13:15
  • @Neolisk Except ConstraintException is part of the DataTable/DataRow stuff, and since SqlException is sealed, you can't inherit from it. Although you can inherit from DbException, and I'd recommend that. – Robert McKee Mar 09 '21 at 00:25