Getting StatusCode, StatusDescription and ResponseUri from System.Net.Http.HttpRequestException

Darren Rose 311 Reputation points
2021-04-01T11:46:29.76+00:00

Hi

My app is throwing a System.Net.Http.HttpRequestException when an API I use (Postmark) can't connect due to in my case proxy issues.

ex.message only gives me "An error occurred while sending the request." which is not much use in diagnosing cause

Looking in ex.message.innerexception I can see "The remote server returned an error: (403) Forbidden." which is more useful but still doesn't solve my problem

If I run the app in VS I can see that in InnerException there is Response which contains more detailed information which contains what I need to know to solve the problem e.g. StatusCode, StatusDescription and ResponseUri

83676-image.png

My question is how can I access these values from my code when not running in debugger as the obvious ex.InnerException.Response.StatusCode doesn't work as "Response is not a member of Exception" despite it appearing as so in debugger

Developer technologies VB
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.5K Reputation points
    2021-04-01T15:02:03.81+00:00

    If you know the possible type of the exception (WebException for example, which can be determined during debugging), then try something like this:

    Try
        '...
    Catch exc As Exception
        Dim web_exc As WebException = TryCast(exc.InnerException, WebException)
        If web_exc IsNot Nothing Then
            Dim response As HttpWebResponse = TryCast(web_exc.Response, HttpWebResponse)
            If response IsNot Nothing Then
                Dim status = response.StatusCode
                '...
            End If
        End If
    End Try
    
    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.