How to determine if an exception is thrown for a referential integrity check

I want to check my catch {} clause if the exception is thrown due to referential integrity violation, at the moment I am going through the method below; is there a better / elegant / more appropriate way to determine if this is a referential integrity exception?

public static bool IsReferencialIntegrityExcpetion(this Exception exception)
            return exception is SqlException &&
                   exception.Message.Contains("The DELETE statement conflicted with the REFERENCE constraint ");



source to share

2 answers

The best you can do is SqlException instead Exception

. Then, instead of relying on the message, you can go to ErrorCode (547). And remember that you can stack exceptions and they will be handled in order (so specify more specific catches first. Your code will look like this:

catch(SqlException sqlEx)
    if(sqlEx.ErrorCode == 547)
catch(Exception ex)
    //General error logic


If you want a complete list of possible error codes, run SELECT * FROM sysmessages

in the databaseMASTER




thrown for any error returned from the database, regardless of what caused it (RI, constraint, type mismatch, size mismatch, etc.). You cannot specifically catch RI-based only exceptions, but you can always check for the exception (broadcast as you do by viewing the post, or preferably by viewing the property Errors

) and throw;

over again (note that this is simple throw;

, not throw ex;

as this keeps the trace stack) unless you really want to handle a specific exception.



All Articles