抛出异常,尽管处于try块中,但仍停止应用程序



我有一个调用API的异步函数,但有时有坏数据,我希望抛出一个异常来阻止其他后续过程的运行。异步过程看起来像这样:

public async Function getInfo(url as string) as task(of string)
Dim htpRes As HttpResponseMessage = Await url.GetAsync().ConfigureAwait(False)
Dim result = htpRes.Content.ReadAsStringAsync.Result
If result = "" Then
Throw New Exception("API Failed")
Else
Return result
End If
End Function

该函数由如下所示的过程调用:


sub hitAllAPIs(apiList As List(Of String))
For each i In apiList
Try
Dim info As String = getInfo(i)
doOtherStuffWithInfo(info)
Catch ex As Exception
logError
End Try
Next
End sub

期望的行为是让'hitAllAPIs'中的forloop保持运行,即使在'getInfo'中抛出异常。相反,发生的是异常被击中并停止代码运行,无论我是在调试模式还是发布模式。如果我不在那里照看它并点击'continue',那么forloop就会停止,程序将不再运行。一旦我点击'continue',顺便说一句,'Catch'就会起作用,错误将被记录下来。

问题是我需要这些都自动发生,而这并没有发生。我不能只是消除异常并检查函数是否为空值,因为这是我的代码的一个非常简化的版本,而且函数实际上到处都被调用。我知道我可以改变我的异常设置,简单地跳过所有像这样的异常,但这甚至发生在发布模式下已经部署的代码。我无法想象我的调试异常会对在发布模式下部署的代码产生影响。在任何情况下,我希望有人能帮助我理解为什么这个异常没有被try块自动处理。

谢谢!

似乎result = "是预期结果,而不是异常。使用Try/Catch是相当繁琐的。异常处理用于处理意外结果。在Function中去掉Throw,在For Each中加入If

Public Async Function getInfo(url As String) As Task(Of String)
Dim htpRes As HttpResponseMessage = Await url.GetAsync().ConfigureAwait(False)
Dim result = htpRes.Content.ReadAsStringAsync.Result
Return result
End Function
Sub hitAllAPIs(apiList As List(Of String))
For Each i In apiList
Dim info As String = getInfo(i)
If info = "" Then
'Add an overload of logError that accepts a string
logError("API failed")
Else
doOtherStuffWithInfo(info)
End If
Next
End Sub

最新更新