views:

50

answers:

3

Hello I have an extended stored procedure that sends an error message.

srv_sendmsg(pSrvProc, SRV_MSG_ERROR, errorNum, SRV_FATAL_SERVER, 1,
            NULL, 0, (DBUSMALLINT) __LINE__, 
            buff,
            SRV_NULLTERM);

I've set the severity to SVR_FATAL_SERVER just as a test to see if I can cause the message to throw an exception in the sql.

In my SQL i'm doing:

BEGIN TRY
    EXEC dbo.xp_somethingCool
    SET @Error = @@ERROR
END TRY
BEGIN CATCH
    PRINT 'AN Error occoured!'
    SELECT ERROR_NUMBER() AS ErrorNumber
          ,ERROR_MESSAGE() AS ErrorMessage;
END CATCH

I would think that when my xp sends the error message the tsql would catch the error and select the error_number and error_message. Instead what ends up happening is that the xp sends the message and the T-SQL continues on its way like nothing happened. The @@Error variable doesn't get set either.

So I was wondering if there was any trick to getting SQL to catch an error from an XP ?

Thanks, Raul

A: 

You should be able to use RAISERROR to throw an exception.

Per comment: Are you not creating your own extended stored proc? If so, you can use throw or do something like 1/0 to throw an exception.

JP Alioto
The question is how can i RAISERROR inside an extended stored procedure ?
HaxElit
A: 

Never raise anything so high. Anything raised with severity above 16 will abort the batch, so your T-SQL catch block never gets a chance to run. Something as high as SVR_FATAL_SERVER will shutdown the server immedeatly.

Remus Rusanu
I don't disagree, but when its raised from an xp it seems to be ignored which is the reason I did it. I wanted to see if it actually did anything. I don't know if there's another api call i can use to cause sql server to actually process the message, or if i'm missing a flag ?
HaxElit
I don't recall exactly, but it may be that the severity is capped for your own protection. Try using 16 for your test.
Remus Rusanu
A: 

You can only test the result from an extended stored proc, and use that to throw an exception.

...
EXEC @rtn = dbo.xp_somethingCool
IF @rtn <> 0
    RAISERROR ...
...

In very simple terms, an extended stored proc is not SQL run by the database engine so you can't issue RAISERROR. See KB 190987 for some more info

gbn