Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Exception not being caught when using RAISERROR function in SQL Server

I have read so much on the RASIERROR function and its requirements for making the exception raise in .NET, but I still can't get the exception to be rasied. Here is the SP snippet:

BEGIN
    RAISERROR('This is a custom error message.', 16, 1);
    RETURN;
END

And here is the .NET code snippet:

        cmd.Connection = conn
        cmd.ExecuteNonQuery()

        'Close the db connection, and local dispose
        conn.Close()

    Catch ex As SQLException
        Dim msg As String = ex.Message
    End Try

So I think I have covered the bases:

  • Severity level above '10' (using 16)
  • Catching SQLException type (although it inherits from Exception so shouldn't matter I would think
  • Using 'ExecuteNonQuery'
  • Within SQL Enterprise Manager, when I run the stored proc directly, I do get the error : "Msg 50000, Level 16, State 1, Line 16 This is a custom error message."

So what am I missing? Any help is appreciated, thanks!

like image 761
atconway Avatar asked Feb 25 '26 12:02

atconway


1 Answers

It works just fine for me:

SqlConnection conn = new SqlConnection("...");
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = conn;
    cmd.CommandText = "errTest";
    cmd.CommandType = System.Data.CommandType.StoredProcedure;
    conn.Open();
    cmd.ExecuteNonQuery();

CREATE PROCEDURE errTest
AS
    RAISERROR('This is a custom error message.', 16, 1);
RETURN;
like image 113
Dustin Davis Avatar answered Feb 27 '26 01:02

Dustin Davis



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!