0

With this code I get the response (error code and message) when an exception from type WebException gets catched.

Dim castExceptionToWebException As WebException = TryCast(ex, WebException)

using r As new StreamReader(castExceptionToWebException.Response.GetResponseStream())
    Dim responseContent = r.ReadToEnd()
    ' DO SOMETHING WITH responseContent
End Using

My questions are: 1.) How could I get the response stream like I did but without casting down to WebException? Is it possible to access it through Exception class 2.) Is there any better work-around?

AdelP
  • 1
  • 2
  • 1
    If you want to catch a `WebException` specifically then you should actually do that, i.e. use `Catch ex As WebException`. Other exception types will then be unhandled at that level unless you have additional `Catch` blocks. – jmcilhinney Jan 17 '19 at 12:36
  • If you can't do that for some reason then a cast is unavoidable because you can't access a member of the `WebException` type without a reference of type `WebException` or something more specific. – jmcilhinney Jan 17 '19 at 12:38
  • thank you for your answer! I'll stick to my solution. – AdelP Jan 21 '19 at 10:05

1 Answers1

0

Replace this with the exceptions you need. Extend the Exception class if you need a custom one.

    Try
        'do stuff
        Dim a = 1 / 0
    Catch ex As DivideByZeroException
        'handle it
    Catch ex As Exception
        'bug out
        Throw ex
    End Try
krizcillz
  • 19
  • 3
  • You should not `Throw ex` but rather just `Throw`. The way you have it, you are truncating the stack trace to the current method. Also, there's no point having a `Catch` block that does nothing but rethrow. If you're not logging the exception or something else, get rid of that `Catch` block. – jmcilhinney Jan 21 '19 at 12:23
  • Disagree entirely, Catch ex allows you to explicitly reference the exception which is useful for error handling and debugging. Unhanded exceptions are a big bug bare of mine. By using the last Catch you're making the explicit _decision_ to ignore the error or pass it back on. – krizcillz Jan 23 '19 at 11:32
  • Making the explicit decision to ignore an unexpected exception is a bad decision. Passing it on has no additional effect to not catching it at all, unless you use `Throw ex` instead of `Throw`, in which case the effect is the undesirable truncation of the stack trace. If you're going to log the exception and then rethrow properly then that's not so bad but, if it's not an specific exception that you can reasonably expect in that situation, why would you catch such an exception just there and not everywhere? – jmcilhinney Jan 23 '19 at 13:11