Thursday, 3 May 2012

How to catch an error in T-SQL and re-throw it again

How to catch an error in T-SQL and  re-throw it again

 

·         We can’t re-throw error like what we do in .net but we can raise new error with same specification, also we can customized the message.

 

BEGIN TRY

              -- this line can be replaced by your own code or proc

        select r = 34/0

END TRY

BEGIN CATCH

          DECLARE

                @ErrorMessage    NVARCHAR(4000),

                @ErrorNumber     INT,

                @ErrorSeverity   INT,

                @ErrorState      INT,

                @ErrorLine       INT,

                @ErrorProcedure  NVARCHAR(200);

 

        SELECT

                @ErrorNumber = ERROR_NUMBER(),

                @ErrorSeverity = ERROR_SEVERITY(),

                @ErrorState = ERROR_STATE(),

                @ErrorLine = ERROR_LINE(),

                @ErrorProcedure = ISNULL(ERROR_PROCEDURE(), '-');

 

        SELECT @ErrorMessage =

                N'Customized Error Message => Error %d, Level %d, State %d, Procedure %s, Line %d, ' +

                        'Message: '+ ERROR_MESSAGE();

 

        /*

                     use any code to send alert or email or save it in a table or any where else!

              */

 

        RAISERROR

                (

                @ErrorMessage,

                @ErrorSeverity,

                @ErrorState,              

                @ErrorNumber,    -- parameter: original error number.

                @ErrorSeverity,  -- parameter: original error severity.

                @ErrorState,     -- parameter: original error state.

                @ErrorProcedure, -- parameter: original error procedure name.

                @ErrorLine       -- parameter: original error line number.

                );

END CATCH;

 

 

 



Poupart Group
Poupart Limited is a company registered in England & Wales with the registration number 0310358. The registered address is 5th Floor, 9 Hatton Street, London, NW8 9PL.


This message is confidential. It may also be privileged or otherwise protected by work product immunity or other legal rules.

If you have received it by mistake, please let us know by e-mail reply and delete it from your system; you may not copy this message or disclose its contents to anyone.

Please send us by fax any message containing deadlines as incoming e-mails are not screened for response deadlines.

The integrity and security of this message cannot be guaranteed on the internet.

No comments:

Post a Comment