开发者

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

开发者 https://www.devze.com 2023-02-08 09:13 出处:网络
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:

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 A开发者_JS百科s 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!


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;


I figured this out; all of the code I posted worked as is 100%. Silly mistake on my part. The severity level was set to '16' but the actual sp had not been executed (I was working off a 'debug' version created by EM that represented the sp; right-click 'debug') and was still set to '10'. Once the update occured .NET immdeatly trapped the exception. Thanks for helping anyways, I do appreciate it.

0

精彩评论

暂无评论...
验证码 换一张
取 消