我可能会采用错误的方式,因为我没有处理网络请求的经验,因此请多多包涵。
我正在尝试执行以下代码:
webClient.DownloadStringAsync(New Uri("http://localhost:8115/"))
当URI可用时,这可以正常工作。但是,如果它不可用(即,如果相应的服务未运行且未公开相关数据),则会收到以下错误消息:
因此,我尝试实现一个try/catch块,如下所示:
If Not webClient.IsBusy Then
Try
webClient.DownloadStringAsync(New Uri("http://localhost:8115/"))
Catch ex As Sockets.SocketException
MsgBox("Error. Service is not running. No data can be extracted.")
End Try
End If
那没有用。 VB.Net仍然不显示消息框。因此,我尝试了其他方法:
If Not webClient.IsBusy Then
Dim req As System.Net.WebRequest
req = System.Net.WebRequest.Create(New Uri("http://localhost:8115/"))
Dim resp As System.Net.WebResponse
Dim ready As Boolean = False
Try
resp = req.GetResponse
resp.Close()
ready = True
Catch ex As Sockets.SocketException
MsgBox("Error. Service is not running. No data can be extracted.")
End Try
If ready Then
webClient.DownloadStringAsync(New Uri("http://localhost:8115/"))
ready = False
End If
End If
它也不起作用。我必须错误地解决此问题。有人可以告诉我正确的做法是什么吗?在运行DownloadStringAsync函数之前,是否可以先检查数据是否存在?
谢谢!
编辑:要将上下文添加到Visual Vincent的回答下的讨论中,这是我的代码。只是一种形式。
Imports System.Net
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim webClient As New System.Net.WebClient
Try
WebClient.DownloadStringAsync(New Uri("http://localhost:8115"))
Catch ex As System.Net.Sockets.SocketException
MessageBox.Show("Error")
Catch ex As System.Net.WebException
MessageBox.Show("Error. Service is not running. No data can be extracted.")
Catch ex As Exception
MessageBox.Show("An error occurred:" & Environment.NewLine & ex.Message)
End Try
End Sub
End Class
最佳答案
WebClient.DownloadStringAsync()
方法不会引发SocketException
,而会引发WebException
(可能将其内部异常设置为SocketException
)。
从the documentation:
SocketException
在大多数情况下仅由原始套接字抛出。然后,System.Net
命名空间的成员通常将它们包装在 WebException
中。
因此,要修复您的代码:
Try
webClient.DownloadStringAsync(New Uri("http://localhost:8115/"))
Catch ex As System.Net.WebException
MessageBox.Show("Error. Service is not running. No data can be extracted.")
End Try
注意:我改为
MessageBox.Show()
是因为MsgBox()
已过时,并且仅存在用于与VB6向后兼容。但是,最佳实践是添加另一个也捕获所有其他异常的
Catch
语句,以免使应用程序崩溃。您还应该记录来自
WebException
的错误消息,因为它可能是由于其他原因引发的,而不仅仅是端点不可用。Try
webClient.DownloadStringAsync(New Uri("http://localhost:8115/"))
Catch ex As System.Net.WebException
MessageBox.Show("Error. Service is not running. No data can be extracted.")
Catch ex As Exception
MessageBox.Show("An error occurred:" & Environment.NewLine & ex.Message)
End Try
关于vb.net - catch SocketException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48842373/