0

Summary: Is there a more elegant solution to the code block below?

Details:

I send an HTTP request to a server with WebRequest. The server might respond with 404 or another HTTP error code. It seems that the only way to handle these HTTP error codes is using try-catch, as in my code below.

I thought error handling like this should only be for 'proper' errors, whereas I consider the HTTP error codes to be legitimate responses. For example, I'd (a) like to do a Select Case on myWebResponse.StatusCode (which might be 200, 202, 404, or something else), and (b) I don't want to have to explicitly re-throw or handle other WebExceptions that might occur; those should just go to whatever error handling happens to be in place at a higher level.

My solution works, but would be neater if I could replace the whole block below with something like myWebResponse=myWebRequest.GetResponse(AcceptHttpErrorStatuses:=True). Is something like this possible, or does everyone use similar try-catch solutions? I suppose I should write a function that does the try-catch. Do others agree that the try-catch approach is ugly, or do you think exception handling is always appropriate for HTTP error codes?

Try
    myWebResponse= myWebRequest.GetResponse()
Catch ex As WebException
    If Not ex.Response Is Nothing Then
        myWebResponse = ex.Response 'So that I can later do Select Case myWebResponse.StatusCode.
    Else
        Throw 'To re-throw proper exceptions like Timeout
    End If
End Try
  • 1
    Unfortunately, WebRequest / WebResponse throw for StatusCodes above 399. It's an old class. You can use HttpClient, it handles the exceptions in a more *modern* way (i.e., it does the same job for you). BTW, WebResponse is disposable, so you need to declare it with a `Using` statement or use the `Finally` block to dispose of it (and it's important that you do). – Jimi Feb 16 '21 at 22:05
  • GSerg: Thanks, that's more or less the same as my question. Jimi: Thanks. I sort of expected that, but thought I'd double check. Good tips about HttpClient and disposing. – Tim von Ahsen Feb 18 '21 at 00:27

0 Answers0