Return server error from function as string?

隐身守侯 提交于 2020-07-10 08:44:24

问题


I have an Excel VBA function that takes a URL and returns a response (source: getHTTP with VBA?).

response = GetHTTP(.ListColumns(colNameURL).DataBodyRange(n).Value)

...

Public Function GetHTTP(ByVal url As String) As String

  With CreateObject("MSXML2.XMLHTTP")
    .Open "GET", url, False: .Send
    GetHTTP = StrConv(.responseBody, vbUnicode)
  End With

End Function

The function works as expected.


However, if there is a problem with the URL (like the server being down), then the VBA editor pops up an error dialog.

Run-time error '-2147467259 (80004005)': Uspecified error

Instead of popping up a dialog, I would like the function to return the error message as a string.

Is there a way to return the server error as a string (without doing the HTTP call more than once)?


What I've tried:

I can get the function to return a pre-defined error message (from a constant).

Public Const InvalidURL = "Problem with URL or Server"


Public Function GetHTTP(ByVal url As String) As String

On Error GoTo ConnectionError:

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", url, False: .Send
        GetHTTP = VBA.StrConv(.responseBody, vbUnicode)
    End With

On Error GoTo 0

Exit Function

ConnectionError:
GetHTTP = InvalidURL

End Function

But that's not quite what I'm looking for. I want to return the true runtime error message (example: the error from the server).


回答1:


It was pretty simple:

GetHTTP = "Problem with URL or server: " & Err.Number & " " & Err.Description

Here's the full function:

Public Function GetHTTP(ByVal url As String) As String

On Error GoTo ConnectionError:

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", url, False: .Send
        GetHTTP = VBA.StrConv(.responseBody, vbUnicode)
    End With

On Error GoTo 0

Exit Function

ConnectionError:
GetHTTP = "Problem with URL or server: " & Err.Number & " " & Err.Description

End Function



回答2:


I'm not a VBA expert, but it is obvious that you need "try - catch" wrapper around your Open()



来源:https://stackoverflow.com/questions/62584612/return-server-error-from-function-as-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!