17.07.2015 Views

Defensive Database Programming - Red Gate Software

Defensive Database Programming - Red Gate Software

Defensive Database Programming - Red Gate Software

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8: <strong>Defensive</strong> Error HandlingAlthough, this time, we did catch our re-thrown error, our method is not robust: wecan by mistake catch other errors and handle them as if they were conversion errors, asshown in Listing 8-16.BEGIN TRY ;RAISERROR('Error saving ticket %s',16,1,'Saving discount blows up: ''Conversion failed whenconverting ...''') ;-- some other codeEND TRYBEGIN CATCH ;DECLARE @ErrorNumber INT ,@ErrorMessage NVARCHAR(4000) ;SELECT @ErrorNumber = ERROR_NUMBER() ,@ErrorMessage = ERROR_MESSAGE() ;IF @ErrorNumber = 245OR @ErrorMessage LIKE '%Conversion failed whenconverting %'BEGIN ;PRINT 'Conversion error caught' ;END ;ELSEBEGIN ;-- handle all other errors herePRINT 'Some other error caught' ;SELECT @ErrorNumber AS ErrorNumber ,@ErrorMessage AS ErrorMessage ;END ;END CATCH ;GOConversion error caughtListing 8-16: Incorrectly handling a ticket-saving error as if it were a conversion error.As we have seen, the inability of T-SQL to re-throw errors may prevent us from robustlyhandling re-thrown errors. If we need to re-throw errors, we should do it on the client.277

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!