Error Handling in T-SQL
Error handling is one of those things in SQL Server that just doesn’t get the attention it deserves. Even a properly constructed stored procedure can still result in error, such as primary key or unique constraint errors.
Why should you care? Consider this real-world example:
You’re a DBA monitoring a well-performing environment. You deploy a new application to production. Suddenly, performance degrades but you do not know why. You look in your error log and see a whole mess of primary key errors. Digging into your newly deployed application, you find that you are now making an extra (and unnecessary) insert to the database, which is resulting in error and causing your performance issues.
This is just one example of many. Fortunately, SQL 2005 has really simplified the error handling process with features such as the Try/Catch block.
The basic components of error handling are:
- Try…Catch block (2005/2008)
- Error identification
- Transaction handling
- Error logging (optional)
- Error notification
As an early holiday gift, here’s a generic error handling process to get you started:
IF OBJECTPROPERTY(OBJECT_ID('dbo.dba_logError_sp'), N'IsProcedure') = 1 BEGIN DROP PROCEDURE dbo.dba_logError_sp; PRINT 'Procedure dba_logError_sp dropped'; END; Go IF OBJECTPROPERTY(OBJECT_ID('dbo.dba_errorLog'), N'IsTable') IS Null BEGIN CREATE TABLE dbo.dba_errorLog ( errorLog_id INT IDENTITY(1,1) , errorType CHAR(3) CONSTRAINT [DF_errorLog_errorType] DEFAULT 'sys' , errorDate DATETIME CONSTRAINT [DF_errorLog_errorDate] DEFAULT(GETDATE()) , errorLine INT , errorMessage NVARCHAR(4000) , errorNumber INT , errorProcedure NVARCHAR(126) , procParameters NVARCHAR(4000) , errorSeverity INT , errorState INT , databaseName NVARCHAR(255) CONSTRAINT PK_errorLog_errorLogID PRIMARY KEY CLUSTERED ( errorLog_id ) ); PRINT 'Table dba_errorLog created'; END; Go SET ANSI_Nulls ON; SET Ansi_Padding ON; SET Ansi_Warnings ON; SET ArithAbort ON; SET Concat_Null_Yields_Null ON; SET NOCOUNT ON; SET Numeric_RoundAbort OFF; SET Quoted_Identifier ON; Go CREATE PROCEDURE dbo.dba_logError_sp ( /* Declare Parameters */ @errorType CHAR(3) = 'sys' , @app_errorProcedure VARCHAR(50) = '' , @app_errorMessage NVARCHAR(4000) = '' , @procParameters NVARCHAR(4000) = '' , @userFriendly BIT = 0 , @forceExit BIT = 1 , @returnError BIT = 1 ) AS /*************************************************************** Name: dba_logError_sp Author: Michelle F. Ufford, http://sqlfool.com Purpose: Retrieves error information and logs in the dba_errorLog table. @errorType = options are "app" or "sys"; "app" are custom application errors, i.e. business logic errors; "sys" are system errors, i.e. PK errors @app_errorProcedure = stored procedure name, needed for app errors @app_errorMessage = custom app error message @procParameters = optional; log the parameters that were passed to the proc that resulted in an error @userFriendly = displays a generic error message if = 1 @forceExit = forces the proc to rollback and exit; mostly useful for application errors. @returnError = returns the error to the calling app if = 1 Called by: Another stored procedure Date Initials Description ---------------------------------------------------------------------------- 2008-12-16 MFU Initial Release **************************************************************** Exec dbo.dba_logError_sp @errorType = 'app' , @app_errorProcedure = 'someTableInsertProcName' , @app_errorMessage = 'Some app-specific error message' , @userFriendly = 1 , @forceExit = 1 , @returnError = 1; ****************************************************************/ SET NOCOUNT ON; SET XACT_Abort ON; BEGIN /* Declare Variables */ DECLARE @errorNumber INT , @errorProcedure VARCHAR(50) , @dbName sysname , @errorLine INT , @errorMessage NVARCHAR(4000) , @errorSeverity INT , @errorState INT , @errorReturnMessage NVARCHAR(4000) , @errorReturnSeverity INT , @currentDateTime SMALLDATETIME; DECLARE @errorReturnID TABLE (errorID VARCHAR(10)); /* Initialize Variables */ SELECT @currentDateTime = GETDATE(); /* Capture our error details */ IF @errorType = 'sys' BEGIN /* Get our system error details and hold it */ SELECT @errorNumber = Error_Number() , @errorProcedure = Error_Procedure() , @dbName = DB_NAME() , @errorLine = Error_Line() , @errorMessage = Error_Message() , @errorSeverity = Error_Severity() , @errorState = Error_State() ; END ELSE BEGIN /* Get our custom app error details and hold it */ SELECT @errorNumber = 0 , @errorProcedure = @app_errorProcedure , @dbName = DB_NAME() , @errorLine = 0 , @errorMessage = @app_errorMessage , @errorSeverity = 0 , @errorState = 0 ; END; /* And keep a copy for our logs */ INSERT INTO dbo.dba_errorLog ( errorType , errorDate , errorLine , errorMessage , errorNumber , errorProcedure , procParameters , errorSeverity , errorState , databaseName ) OUTPUT Inserted.errorLog_id INTO @errorReturnID VALUES ( @errorType , @currentDateTime , @errorLine , @errorMessage , @errorNumber , @errorProcedure , @procParameters , @errorSeverity , @errorState , @dbName ); /* Should we display a user friendly message to the application? */ IF @userFriendly = 1 SELECT @errorReturnMessage = 'An error has occurred in the database (' + errorID + ')' FROM @errorReturnID; ELSE SELECT @errorReturnMessage = @errorMessage; /* Do we want to force the application to exit? */ IF @forceExit = 1 SELECT @errorReturnSeverity = 15 ELSE SELECT @errorReturnSeverity = @errorSeverity; /* Should we return an error message to the calling proc? */ IF @returnError = 1 RAISERROR ( @errorReturnMessage , @errorReturnSeverity , 1 ) WITH NoWait; SET NOCOUNT OFF; RETURN 0; END Go
You would then call this proc in the following manner:
BEGIN Try /* If a business logic error exists, then call this proc */ IF 1 != 1 EXECUTE dbo.dba_logError_sp @errorType = 'app' , @app_errorProcedure = 'yourStoredProcedureName' , @app_errorMessage = '1 does not equal 1!' , @forceExit = 1; /* Start a new transaction */ BEGIN TRANSACTION; /* Do something */ /* If you have an open transaction, commit it */ IF @@TRANCOUNT > 0 COMMIT TRANSACTION; END Try BEGIN Catch /* Whoops, there was an error... rollback! */ IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION; /* Grab our proc parameters */ SET @errorParameters = '@myVariable = ' + @myVariable; /* Return an error message and log it */ EXECUTE dbo.dba_logError_sp @procParameters = @errorParameters; END Catch;
Some things to keep in mind:
- Error handling is not a “one-size-fits-all” process. Make sure you’re handling the error appropriately for your environment.
- Be careful when working with nested transactions; you can sometimes get unexpected results.
- Only errors with a severity levels greater than 10 will be caught by the Catch block.
- You can initiate an error within your stored procedure by using RaisError().
Happy coding holidays!
Comments
8 Comments on Error Handling in T-SQL
-
SQLBatman on
Wed, 17th Dec 2008 7:51 am
-
Rob Boek on
Wed, 17th Dec 2008 8:05 am
-
Michelle Ufford on
Wed, 17th Dec 2008 8:17 am
-
Stephen Dyckes on
Fri, 19th Dec 2008 12:07 pm
-
Jamie Thomson on
Sun, 21st Dec 2008 5:29 am
-
Michelle Ufford on
Sun, 21st Dec 2008 7:38 am
-
links for 2009-01-08 « News to Me on
Thu, 8th Jan 2009 8:01 am
-
Monitoring Process for Performance Counters : SQL Fool on
Wed, 16th Sep 2009 10:22 am
nice post. this is often one of the things i find lacking in dev code and i try to explain why it is so important. typically it takes an “incident” in order to hammer home the point.
Those code boxes give very strange results in Google Reader.
Thanks for the head’s up, Rob! I’ll take a look and see if I can fix it.
Thanks for a great reminder about my lack of error handling. It lays out a great method for SQL2005. Too bad I am still stuck in 2000 with most of my environmnents, but there are ways to handle it there as well.
In the code above I think I’m writing in saying that whoever called the sproc where the error occurred would never know about the error – hence they would assume that whatever activity they were doing had been committed. This strikes me as being a very bad thing.
There needs to be a way of reporting back to the caller than error occurred. Logging the error is all well and good (and very much best practice) but you MUST report back to the caller. As a rule I catch the error, log it, and then rethrow it back to the caller and have it handled at the top of the call stack – probably by reporting it back to the person that instigated the activity.
-Jamie
Hi Jamie,
The error proc, dba_logError_sp , will indeed return the error to the calling app if @returnError = 1, which is the default behavior.
/* Should we return an error message to the calling proc? */
IF @returnError = 1
RAISERROR
(
@errorReturnMessage
, @errorReturnSeverity
, 1
) WITH NOWAIT;
The reason I wrote the return section this way is that I’ve used the error logging proc as a form a of debug; if a condition occurs that I want to be logged but I don’t want to return an error, I set @returnError = 1 and @forceExit = 0.
To your point, you could modify the error proc to return -1 and have your application check for and handle errors based on the return value. This just depends on your application preferences.
[...] Error Handling in T-SQL (tags: sql howto sqlserver error) [...]
[...] Getting an error about dba_logError_sp? Take a look at my error handling proc. [...]
Tell me what you're thinking...
and oh, if you've enjoyed the post, please consider subscribing to my blog. ![]()





