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