如何在 vb.net 中使用自定义消息处理 "Could not open a connection to SQL Server"

How to handle "Could not open a connection to SQL Server" with custom message in vb.net

在加载 VB.NET 表单时,如果 SQL 服务器数据库脱机或无法访问,是否有任何方法可以向用户提供您自己的消息! 是的,我不想使用 Try/Catch,因为它会显示发生的所有类型的错误,例如:

Try
catch ex as exception
MessageBox.Show("Not Completed Because OF The Following Error " & "%" & ex.Message & "%", "Error", _
                        MessageBoxButtons.OK, MessageBoxIcon.Error)
end try

但是如果有一种方法可以使用 Try&Catch 来解决特定错误,那么我可以接受!

Visual Basic 支持用户过滤的异常。用户过滤的异常处理程序根据您为异常定义的要求捕获和处理异常。这些处理程序使用带有 When keyword.You 的 Catch 语句可以修改您的 try catch 以过滤异常,例如

Try

Catch sqlEx as SqlException
   'Do something about the exception
Catch ex as Exception
   Throw 'Re-throw any other exception
End Try

你也可以根据几个 sql 异常本身来深度过滤异常,比如

Try

Catch sqlEx as SqlException When sqlEx.Number = [SQL error number]
   'Do something about the exception
Catch sqlEx as SqlException When sqlEx.Number = [Another SQL error number]
   'Do something about the exception
Catch sqlEx as SqlException  'all other SQL exceptions
   'Do something about the exception
Catch ex as Exception
   Throw 'Re-throw any other exception
End Try

更多参考,VB exception filtering, Pros and cons of Exception filtering, how to catch sql exception

你可以处理 SqlException and decide the message based on the Number 属性.

Try

    Open the connection and execute command

Catch sqlEx As SqlException
    Select Case sqlEx.Number
        Case -1, 2, 53
            MessageBox.Show("Connection Failed")
        Case Else
            MessageBox.Show("General SQL Error Messagge")
    End Select
Catch ex As Exception
    MessageBox.Show("General Error")
End Try

您可以找到错误列表 here

  • Error -1
    An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: SQL Network Interfaces, error: 28
  • Server doesn't support requested protocol) (Microsoft SQL Server, Error: -1).

  • Error 2
    An error has occurred while establishing a connection to the server. When connecting to SQL Server, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server ) (.Net SqlClient Data Provider)

  • Error 53
    An error has occurred while establishing a connection to the server. When connecting to SQL Server, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server ) (.Net SqlClient Data Provider).