1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[SQL] How to catch the SQL Server network-related errors in C# correctly?

Discussão em 'Outras Linguagens' iniciado por Stack, Outubro 9, 2024 às 14:12.

  1. Stack

    Stack Membro Participativo

    I want to catch all network-related exceptions from SQL Server (connection lost, timeout, etc.) and show a warning dialog to the end user when SQL Server instance suddenly goes down.

    The SqlException contains the list of errors which is supposed to show the exact error to me.

    https://learn.microsoft.com/en-us/d...lient.sqlerror.number?view=netframework-4.8.1

    However, based on my tests, whenever I stop the SQL Server service, the only property in this collection contains SqlError.Number property set to "-1".

    if (ex is SqlException sqlException)
    {
    int number = ex.Number; // -1
    }


    The error message says


    A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

    So, my questions are

    • Is it safe to assume that if SqlError collection contains only a record with a number "-1", then it's a network-related issue?
    • If not, how can I get this specific "provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified" information from the SqlException object?
    • If I try to get that number "26" by parsing the error message, that will be error-prone, right? I assume these error messages can be localized to other languages based on the system settings.
    • Is there any documentation of all possible issues related to losing the connection to the SQL Server instance and a proper recommendation how to catch it in C#?

    I tried to find a documentation about those issues, but couldn't find any helpful link about it.

    Continue reading...

Compartilhe esta Página