Catch SQL raise error in C#
Asked Answered
A

3

32

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

Ahmed answered 2/3, 2014 at 11:13 Comment(2)
And what is your exact problem? Doesn't the try-catch work?Giuliana
Running in the debugger, are you even getting an exception that ends up in the catch clause, and if so, what's in ex.Errors[0].Number?Cricket
M
62

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.

Macario answered 2/3, 2014 at 11:24 Comment(0)
C
11

Your if statement is where things fail. Assuming that the first error in the collection is indeed the one you are looking for (it might not be).

SqlError.Number is not the value that you set in RAISERROR.

Use SqlError.Class to retrieve the severity of the error, or SqlError.State to check the state (both are -10 in your example. so difficult to tell which out you mean):

catch (SqlException ex)
{
    bResult = false;                   
    if (ex.Errors[0].Class == -10)
    {
        CommonTools.vAddToLog("bInsertNewUser", "ManageUsers", ex.Message);
        if ((savePoint != null))
            savePoint.Rollback();
    }
} 
Cystocarp answered 2/3, 2014 at 11:19 Comment(0)
H
0

Use an error code within 11-16, or just use 16 for a "general" case.

RAISERROR('Already exists',16,1)

Why? Here's my summary of https://learn.microsoft.com/en-us/sql/relational-databases/errors-events/database-engine-error-severities?view=sql-server-2017:

SQL RAISERROR -> C#:

  • 0-10 = fyi*
  • 11-16 = you can fix it**
  • 17-19 = get admin help
  • 20-24 = definitely get admin help***

*(don't throw anything) ┬──┬

**(16 = general)

***(fatal error)

Hurty answered 8/12, 2018 at 3:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.