SqlException constraint violation

I am working on an asp.net application. Is there a way, when to catch a SqlException, to know which restriction has been violated?

+4
source share
5 answers

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

Although it is true that the SqlException itself provides the Number property, it is inaccurate if several errors occur in the same batch, and therefore it is better to check the collection of errors.

+7
source
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 } } } 
+4
source

You should add an exception handler to throw a ConstraintException if I understood your question correctly

 try { } catch(ConstraintException exc) { //exc.Message } 
+2
source

Do you allow an exception? If you do not catch it and disable user errors in web.config, I believe that it will display it in your browser. If you catch it, I would put a breakpoint in the catch section and check for an exception there.

0
source

It is best to catch this catch exception in C # code.

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

You can create your own exception and throw it from your data level, otherwise you can directly catch the exception as described above.

 using System; public class UniqueConstraintException : Exception { } 
-1
source

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


All Articles