Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Exception in LINQ to SQL

Tags:

linq-to-sql

I want to throw a custom exception when my Insert fails, which violates PK / FK relationship. Now, LINQ TO SQL throws SQLException, I want to throw a more specific exception like CategoryException.

like image 428
pokrate Avatar asked Dec 17 '25 20:12

pokrate


2 Answers

When you catch the SQLException you can check its Number property or navigate to its Errors property and check if it contains any SqlError with number 547 - that should be constraints violation. If you need details about what constraint was violated and on which table you must really parse the message as @tyrongower mentioned. The pattern for the message is:

The %ls statement conflicted with the %ls constraint "%.*ls". The conflict occurred in database "%.*ls", table "%.*ls"%ls%.*ls%ls.

Edit:

Depending on the type of application you are developing you should be aware of localization. SQL server can localize its error messages so if you deploy the application to the server using different locale setting your exception message parsing will not work.

like image 112
Ladislav Mrnka Avatar answered Dec 20 '25 04:12

Ladislav Mrnka


You may need to catch the SQLException and parse the message body, then throw your desired custom exception.

like image 25
TheRealTy Avatar answered Dec 20 '25 03:12

TheRealTy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!