Dezryth
Dezryth

Reputation: 243

SQL Server TRY...CATCH Is Not Catching An Error

BEGIN TRY
    EXEC N'EXEC sp_testlinkedserver N''[MyLinkedServer]'';';
END TRY
BEGIN CATCH
    SELECT 'LinkedServerDown' AS Result
    RETURN
END CATCH
SELECT TOP(1) FirstName FROM [MyLinkedServer].TestDatabase.dbo.Customer

My first experience with using a TRY...CATCH in SQL Server does not have me impressed so far.

I've stopped the SQL Service on my linked server to attempt to test a situation where our linked server is down, inaccessible, etc.

Instead of catching any error, this code just throws the "Login timeout expired" and "network-related or instance-specific error has occurred..." error and ceases execution of the rest of the code.

Is my SQL TRY...CATCH block not set up correctly?

Upvotes: 6

Views: 3535

Answers (4)

KUL
KUL

Reputation: 491

You can perform a tricky trick with creating a temporary procedure from text.

declare @strQueryProc varchar(max), @strQuery varchar(max)
set @strQuery = 'select 2/0'

if (object_id('tempdb..#tempProcExec') != 0)
    drop procedure #tempProcExec

set @strQueryProc = 'create procedure #tempProcExec as '+@strQuery
exec(@strQueryProc)

begin try
    exec #tempProcExec
end try
begin catch
    select ERROR_MESSAGE()
end catch

Upvotes: 0

Abubakar Riaz
Abubakar Riaz

Reputation: 340

You need to create your end testlinkedserver stored procedure. This will also capture login time out errors.

exec dbo.USP_testlinkedserver 'myServerNameHere'

The definition is mentioned below:

CREATE PROCEDURE USP_testlinkedserver 
    @ServerName sysname
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @statement NVARCHAR(MAX), @errorMessage NVARCHAR(MAX)

    SET @statement = N'SELECT * FROM OPENQUERY('+QUOTENAME(@ServerName,'[')+', ''SELECT 1'')'

BEGIN TRY
    -- run the query
    EXEC sp_executesql @stmt = @statement;
END TRY
BEGIN CATCH
    -- show custom message
    SET @errorMessage=QUOTENAME(@ServerName,'[') + ' linked server is not available. ' + ERROR_MESSAGE()
    Raiserror(@errorMessage,16,1)
END CATCH;

END

Upvotes: 0

Krishnraj Rana
Krishnraj Rana

Reputation: 6656

As per the MSDN, what sp_testlinkedserver do is

Tests the connection to a linked server. If the test is unsuccessful the procedure raises an exception with the reason of the failure.

So when you compile your code (SP), sp_testlinkedserver checks for connection. But you can defer this and capture it by using dynamic SQL.

Like this -

BEGIN TRY
    EXEC sp_executesql N'EXEC sp_testlinkedserver [192.168.51.81];';
END TRY
BEGIN CATCH
    SELECT 'LinkedServerDown' AS Result
END CATCH

Upvotes: 4

Sandip Bantawa
Sandip Bantawa

Reputation: 2880

From MSDN

Errors Unaffected by a TRY…CATCH Construct

TRY…CATCH constructs do not trap the following conditions:

  1. Warnings or informational messages that have a severity of 10 or lower.
  2. Errors that have a severity of 20 or higher that stop the SQL Server Database Engine task processing for the session. If an error occurs that has severity of 20 or higher and the database connection is not disrupted, TRY…CATCH will handle the error.
  3. Attentions, such as client-interrupt requests or broken client connections.
  4. When the session is ended by a system administrator by using the KILL statement.

The following types of errors are not handled by a CATCH block when they occur at the same level of execution as the TRY…CATCH construct:

  1. Compile errors, such as syntax errors, that prevent a batch from running.
  2. Errors that occur during statement-level recompilation, such as object name resolution errors that occur after compilation because of deferred name resolution.

Upvotes: 1

Related Questions