Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[HttpClient] Add a method to validate the status code of the response #34046

Closed
@mnapoli

Description

@mnapoli

Description

Checking all error cases of a response is repetitive work. I understand why the HTTP client does not throw exceptions on HTTP errors.

However, a helper method could make things simpler for most cases: a new $response->assertIsSuccessful() method could throw detailed errors if the HTTP status code is >=300.

Example

// Before
$response = $http->request('PATCH', '<url>', ...);
if ($response->getStatusCode() === 404) {
    throw new NotFound('Resource not found');
}
if ($response->getStatusCode() === 400) {
    throw new RuntimeException('We need to fix our code : ' /* add info about the response here */);
}
if ($response->getStatusCode() >= 500) {
    throw new RuntimeException('API error, we need to retry later');
}
// and I'm missing some cases here

// After
$response = $http->request('PATCH', '<url>', ...);
// Throws if response is not 200
$response->assertIsSuccessful();

From the documentation it seems the only way to achieve a similar behavior is to try to get the content of the response. But it would make more sense to have a method dedicated to that.

WDYT?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions