SQL Server TRY...CATCH Is Not Catching An Error
Asked Answered
G

4

6
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?

Ginsburg answered 14/10, 2015 at 16:20 Comment(2)
What is the severity of the error you are getting? If its higher than 20, try catch will not trap the errorPrimm
How can I tell what the severity of the error is?Ginsburg
C
4

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
Commerce answered 14/10, 2015 at 16:31 Comment(3)
I wish this worked! But instead I get the same error messages and results as before.Ginsburg
@Dezryth: I have checked above code in my sql server instance and it works perfectly fine. see my edited answer(included my local linked server ip).Commerce
@Dezryth: Remove quote(') from the statement and try this query - EXEC sp_executesql N'EXEC sp_testlinkedserver [MyLinkedServer];'Commerce
D
1

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.
Doloresdolorimetry answered 14/10, 2015 at 16:38 Comment(1)
So basically, I can't do what I'm trying to do here? I want to be able to test if a server is up before running some subsequent code that accesses that server. If not, return some default selection.Ginsburg
C
0

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
Calamondin answered 19/4, 2019 at 12:3 Comment(0)
G
0

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
Grandpapa answered 27/9, 2024 at 8:21 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.