I have a stored procedure that gives a friendly enough error that I want to show to the users but when I call it from .net it comes out twice. When I call the proc from sql server management studio it only comes out once.
Here is a cutdown version of the stored proc:
ALTER PROC [Production].[spDoSomething] (
@PassedID int)
AS
BEGIN
DECLARE @ErrorString nvarchar(500);
BEGIN TRY
...
RAISERROR('Bad things are happening.', 11 /*severity*/, 1 /*state*/);
...
END TRY
BEGIN CATCH
SET @ErrorString = 'Error found:' + ERROR_MESSAGE();
PRINT @ErrorString;
RAISERROR(@ErrorString, 11 /*severity*/, 1 /*state*/);
END CATCH
END
I call this in some c# code using ExecuteNonQuery()
of a System.Data.SqlClient.SQLCommand
object then I catch a System.Data.SqlClient.SQLException
but the Message contains
"Error: Found Bad things are happening.\nError Found: Bad things are happening."
Does anyone know a reason why it comes out twice?
This is on sql server 2008 and .net 3.5
Please comment the "PRINT @ErrorString;" statement. When SQL Engine throws an error, it would displays all the messages are available in the message stack.
Reason:
Try to run below code snap.
CREATE PROCEDURE ErrorHandler
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @ErrorString nvarchar(500);
BEGIN TRY
RAISERROR('Bad things are happening.', 11 /*severity*/, 1 /*state*/);
END TRY
BEGIN CATCH
SET @ErrorString = 'Error found:' + ERROR_MESSAGE();
PRINT @ErrorString;
PRINT 'Stack overflow'
RAISERROR(@ErrorString, 11 /*severity*/, 1 /*state*/);
END CATCH
END
GO
EXEC ErrorHandler
SQL engine generates 3 messages;
1. 1st for PRINT @ErrorString;
2. 2nd for PRINT 'Stack overflow'
3. 3rd for RAISERROR(@ErrorString, 11 /*severity*/, 1 /*state*/);