首页 > 解决方案 > 尽管处于尝试块中,但抛出异常停止应用程序

问题描述

我有一个调用 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

即使在“getInfo”中抛出异常,所需的行为是让“hitAllAPIs”中的 forloop 继续运行。相反,无论我处于调试模式还是发布模式,都会发生异常并阻止代码运行。如果我不在那儿照看它并点击“继续”,那么 forloop 将停止并且程序将不再运行。顺便说一句,一旦我点击“继续”,“Catch”就会起作用,并且会记录错误。

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

谢谢!

标签: vb.net

解决方案


似乎 result = "" 是预期结果而不是例外。使用 Try/Catch 相当繁琐。异常处理是为了意外的结果。去掉ThrowinFunction并添加and IfFor Each

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

推荐阅读