Catch SQL raise error in C#

Raed Alsaleh picture Raed Alsaleh · Mar 2, 2014 · Viewed 38.7k times · Source

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# ?

Answer

Steve picture Steve · Mar 2, 2014

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.