From aa5fc277a4f5508013d571341ade0c3886d4d00e Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Mon, 13 Nov 2023 10:31:12 +0100 Subject: [PATCH] Fix error handling in Stream::getContents() (#252) --- src/Stream.php | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/Stream.php b/src/Stream.php index d3bd78d..63b7d6d 100644 --- a/src/Stream.php +++ b/src/Stream.php @@ -260,11 +260,19 @@ public function getContents(): string throw new \RuntimeException('Stream is detached'); } - if (false === $contents = @\stream_get_contents($this->stream)) { - throw new \RuntimeException('Unable to read stream contents: ' . (\error_get_last()['message'] ?? '')); + $exception = null; + + \set_error_handler(static function ($type, $message) use (&$exception) { + throw $exception = new \RuntimeException('Unable to read stream contents: ' . $message); + }); + + try { + return \stream_get_contents($this->stream); + } catch (\Throwable $e) { + throw $e === $exception ? $e : new \RuntimeException('Unable to read stream contents: ' . $e->getMessage(), 0, $e); + } finally { + \restore_error_handler(); } - - return $contents; } /**