From 7ed28441a412ca15159e4b4ac3dde2c9f6a55350 Mon Sep 17 00:00:00 2001 From: Typeonce Date: Fri, 24 May 2024 15:59:40 +0300 Subject: [PATCH] Add error message to failed requests (#1722) Co-authored-by: sc Co-authored-by: Alex Bouma Co-authored-by: Michi Hoffmann --- src/HttpClient/HttpClient.php | 5 ++++- tests/HttpClient/HttpClientTest.php | 23 +++++++++++++++++++++++ tests/testserver/index.php | 2 +- 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/HttpClient/HttpClient.php b/src/HttpClient/HttpClient.php index 779088d25..a5c64847c 100644 --- a/src/HttpClient/HttpClient.php +++ b/src/HttpClient/HttpClient.php @@ -89,6 +89,7 @@ public function sendRequest(Request $request, Options $options): Response curl_setopt($curlHandle, \CURLOPT_PROXYUSERPWD, $httpProxyAuthentication); } + /** @var string|false $body */ $body = curl_exec($curlHandle); if ($body === false) { @@ -105,6 +106,8 @@ public function sendRequest(Request $request, Options $options): Response curl_close($curlHandle); - return new Response($statusCode, $responseHeaders, ''); + $error = $statusCode >= 400 ? $body : ''; + + return new Response($statusCode, $responseHeaders, $error); } } diff --git a/tests/HttpClient/HttpClientTest.php b/tests/HttpClient/HttpClientTest.php index e6b0d23f0..583ba7eff 100644 --- a/tests/HttpClient/HttpClientTest.php +++ b/tests/HttpClient/HttpClientTest.php @@ -71,9 +71,32 @@ public function testClientMakesUncompressedRequestWhenCompressionDisabled(): voi $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals($response->getStatusCode(), $serverOutput['status']); $this->assertEquals($request->getStringBody(), $serverOutput['body']); + $this->assertEquals($response->getError(), ''); $this->assertEquals(\strlen($request->getStringBody()), $serverOutput['headers']['Content-Length']); } + public function testClientReturnsBodyAsErrorOnNonSuccessStatusCode(): void + { + $testServer = $this->startTestServer(); + + $options = new Options([ + 'dsn' => "http://publicKey@{$testServer}/400", + ]); + + $request = new Request(); + $request->setStringBody('test'); + + $client = new HttpClient('sentry.php', 'testing'); + $response = $client->sendRequest($request, $options); + + $this->stopTestServer(); + + $this->assertFalse($response->isSuccess()); + $this->assertEquals(400, $response->getStatusCode()); + + $this->assertEquals($request->getStringBody(), $response->getError()); + } + public function testThrowsExceptionIfDsnOptionIsNotSet(): void { $this->expectException(\RuntimeException::class); diff --git a/tests/testserver/index.php b/tests/testserver/index.php index b7f0709a4..8b7f3ec08 100644 --- a/tests/testserver/index.php +++ b/tests/testserver/index.php @@ -53,4 +53,4 @@ http_response_code($status); -return 'Processed.'; +echo $body;