Error Handling in T-SQL & Email Notification

This is something I have found useful when you need to capture the exact error message while running the stored procedure in MSSQL database and send automated emails with exact error details to operation guys or to a automated incident management tool which can create ticket for the failure with the email content 

We should design the stored procedure in try catch (TRY...CATCH) method and pass the below script in the catch block. 

USE TESTDB
GO
CREATE PROC TEST_SP
AS
BEGIN TRY

--- ACTUAL CODE

END TRY

BEGIN CATCH
PRINT DB_NAME() +'.'+ OBJECT_SCHEMA_NAME(@@PROCID) + '.' + OBJECT_NAME(@@PROCID) + ' LOAD - FAILED'

DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE();
DECLARE @ErrorSeverity INT = ERROR_SEVERITY();
DECLARE @ErrorState INT = ERROR_STATE();
DECLARE @LDDATE VARCHAR(40) =CONVERT(VARCHAR(20),GETDATE(),112);
DECLARE @BDY NVARCHAR(MAX) = 'ServerName:'+ @@SERVERNAME + CHAR(10) + 'ErrorMessage: '+@ErrorMessage + CHAR(10) + 'ErrorSeverity: '+CAST(@ErrorSeverity AS VARCHAR(20)) + CHAR(10) +'ErrorState: '+CAST(@ErrorState AS VARCHAR(20));
DECLARE @SUB NVARCHAR(MAX) = @@SERVERNAME + ' : ' + 'FAILURE : ' + DB_NAME() +'.'+ OBJECT_SCHEMA_NAME(@@PROCID) + '.' + OBJECT_NAME(@@PROCID) + ' : ' + @LDDATE 
EXEC msdb.dbo.sp_send_dbmail 
@profile_name='email_profile_name',
@recipients='operation_emailaddress@domain.com',
@subject=@SUB,
@body =  @BDY;
THROW
END CATCH 


The above code will send out email notification with exact error message which sql server returns while execution.

Tip: You can see I have used THROW(link) statement inside my catch block. In general when we use try and catch block the overall execution of procedure will be always successful even if the procedures fails, this the default behavior of try catch block use case. if you wish to show the status of the procedure as failure use THROW statement inside your catch block.

Prerequisites for using this approach


  1. Microsoft SQL Server on premise database installation
  2. Email Profile created in MS SQL server  Database Mail Profile

Disclaimer: All information shared above are based on real use cases while working on a typical data projects. If there is some information which is missing or there is any scope of improvement in the above content I always welcome such suggestions.

Comments

Popular posts from this blog

Microsoft Power Automate -- Timeout Limitation of 120 Sec in SQL Actions -- Solution

How to parse XML response from REST API in Azure Data Factory

Power BI Usage Metrics with the help of Power Automate - PBI Analytics