One very useful addition to a database I have found recently is to capture database errors in a try...catch block and storing the information in a table. Here is what I did:
Table to store the error information:
DBErrorID INT IDENTITY
,Raised DATETIME NULL CONSTRAINT DF_DBErrors_Raised DEFAULT (GETDATE())
,Number INT NULL
,Severity INT NULL
,StateNumber INT NULL
,StoredProcedure NVARCHAR(128) NULL
,Line INT NULL
,ErrorMessage NVARCHAR(4000) NULL
,CONSTRAINT PK_DBErrors PRIMARY KEY CLUSTERED (DBErrorID)
) ON [PRIMARY]
Then I wrote a stored procedure to write to the table:
AS
BEGIN
DECLARE @DBErrorsExist bit;
SET NOCOUNT ON;
SELECT TOP (1) @DBErrorsExist = TableExists FROM dbo.efn_TableExists('DBErrors');
IF (@DBErrorsExist = 1)
BEGIN
INSERT INTO DBErrors (Number, Severity, StateNumber, StoredProcedure, Line, ErrorMessage) VALUES (
ERROR_NUMBER(),
ERROR_SEVERITY(),
ERROR_STATE(),
ERROR_PROCEDURE(),
ERROR_LINE(),
ERROR_MESSAGE());
RETURN -2;
END
ELSE
BEGIN
RETURN -1;
END;
END;
Then where I wanted to capture any errors i.e. in a stored procedure I did the following:
... Stored proc code
END TRY
BEGIN CATCH
EXEC dbo.DBErrorInsert;
END CATCH
When an error occurs in the try...catch block it writes the error information including the line the error was triggered to a record in the table.
