Skip to content

[API Proposal]: Add body content to HttpRequestException #86095

@StephenCleary

Description

@StephenCleary

Background and motivation

The existing HttpClient / HttpRequestException API does not provide a pit of success when API calls fail. System.Net.Http.HttpRequestException: Response status code does not indicate success: 400 (Bad Request). isn't terribly useful since it throws away all the details of the error, usually present in the body of the response. This applies to all failing status codes.

This is particularly impactful for developers learning a new API, as well as developers "testing the waters" of C# - API calls are something they're often familiar with, yet the first attempt often has some mistake in it. Experienced developers are also regularly frustrated by this because they have to add more boilerplate logging code after the call failed with a useless log message and then wait for it to fail again.

Minimum request: if the body content is a textual MIME type, include it (truncated if necessary) in HttpRequestException.Message.

Stretch goal: also handle binary information, adding a member to HttpRequestException to access the body content as bytes (buffered in memory, so this would also need to be truncated).

API Proposal

(No API change; just a behavior change)

The default HttpRequestException.Message would include the content as a string, if possible.

API Usage

catch (HttpRequestException ex)
{
  logger.LogError(ex, "Call failed"); // ex.Message now includes body as string
}

Alternative Designs

No response

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions