Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch SQL raise error in C#

I generate the raise error in SQL procedure:

RAISERROR('Already exist',-10,-10)

but I can not catch it using the following code in C#

catch (SqlException ex) {     bResult = false;                        if (ex.Errors[0].Number == -10)     {         CommonTools.vAddToLog("bInsertNewUser", "ManageUsers", ex.Message);         if ((savePoint != null))             savePoint.Rollback();     } }  

How can I catch the raised error in C# ?

like image 850
Raed Alsaleh Avatar asked Mar 02 '14 11:03

Raed Alsaleh


People also ask

How do I catch an error message in SQL Server?

When called in a CATCH block, ERROR_MESSAGE returns the complete text of the error message that caused the CATCH block to run. The text includes the values supplied for any substitutable parameters - for example, lengths, object names, or times. ERROR_MESSAGE returns NULL when called outside the scope of a CATCH block.

How can we increase error in catch block in SQL Server?

CATCH blocks can use RAISERROR to rethrow the error that invoked the CATCH block by using system functions such as ERROR_NUMBER and ERROR_MESSAGE to retrieve the original error information. @@ERROR is set to 0 by default for messages with a severity from 1 through 10.

How do I catch an exception in SQL?

CATCH construct catches all execution errors that have a severity higher than 10 that do not close the database connection. A TRY block must be immediately followed by an associated CATCH block. Including any other statements between the END TRY and BEGIN CATCH statements generates a syntax error.

Can we use try catch in SQL function?

Note that you cannot use TRY... CATCH blocks inside T-SQL UDFs. If you have to capture errors that occur inside a UDF, you can do that in the calling procedure or code.


1 Answers

RAISERRORs with a SEVERITY value under or equal to 10 are not caught on the C# side because I suppose they are considered just warnings as you can see from the list at Database Engine Error Severities.

SEVERITY values between 11 and 16 are errors that can be corrected by the user, so, for example, you can try with:

RAISERROR('Already exist',16,1) 

Otherwise, you could choose another error code from the list above or, if you really need it, prepare your own custom error message using sp_addmessage.

like image 151
Steve Avatar answered Sep 20 '22 18:09

Steve