-1

Context:

In System.Net.Http HttpResponseMessage Dotnet has offered a method EnsureSuccessStatusCode(). I know, It's a convenient method that throws an exception if the HTTP response status code indicates an error.

But once I read in the C# book (Microsoft Exam 70-483 Second Edition) they suggested not every time throw exceptions for obvious error handling but rather keep it for unforeseen scenarios. It's crucial to strike a balance and use exceptions judiciously, reserving them for exceptional situations. Propagating exceptions again and again by breaking the application flow can negatively impact the overall performance of the application..., becomes harder for profiling tools to identify the root cause of performance issues... and many more, which I believe makes pretty sense.

Question:

I am just wondering if it's such a bad practice then why Dotnet has offered such a method? Isn't it good to make use of IsSuccessStatusCode and build an error-handling mechanism, like return codes or error flags? which might be more efficient.

Malik Khalil
  • 6,454
  • 2
  • 39
  • 33
  • 2
    That doesn't make sense. A program doesn't have to efficiently not do its job. – Hans Passant Jun 04 '23 at 18:51
  • 2
    Depends how often you expect an exception to be thrown. If it's rarely thrown, and such an event is exceptional and expected to take time to clear up then it doesn't matter. But don't use it as normal control flow (such as `int.Parse`) – Charlieface Jun 04 '23 at 19:31
  • You are right @Charlieface but I think it's obvious that network calls can succeed or fail, at least on this point we can make informed decisions and save the system by not putting extra strain. – Malik Khalil Jun 04 '23 at 21:12
  • 2
    @MalikKhalil: *"I think it's obvious that network calls can succeed or fail"* Indeed. But in a huge amount of use cases, a failing network call is (a) "an exceptional situation" and/or (b) a situation the developer wishes to be handled by their global exception handler. In both cases, throwing an exception is the right thing to do. In those rare cases where neither (a) nor (b) applies, then, yes, checking `IsSuccessStatusCode` is more appropriate. – Heinzi Jun 04 '23 at 21:26
  • That makes a lot of sense. Thanks, @Heinzi – Malik Khalil Jun 04 '23 at 21:29
  • @MalikKhalil: Glad to hear it helped. I have converted my comment into an answer. – Heinzi Jun 04 '23 at 21:31

1 Answers1

0

In a large amount of use cases, a failing network call is

  1. "an exceptional situation" and/or
  2. a situation the developer wishes to be handled by their global exception handler.

In both cases, throwing an exception is the right thing to do, and EnsureSuccessStatusCode provides a convenient way to do that.

In those rare cases where neither (a) nor (b) applies, then, yes, checking IsSuccessStatusCode is more appropriate.

Heinzi
  • 167,459
  • 57
  • 363
  • 519