From 5f80208fc827bbe4939465bdda8e91536050954a Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Fri, 10 Nov 2023 11:00:41 +0100 Subject: [PATCH] Fix error handling in Stream::getContents() --- src/Stream.php | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/src/Stream.php b/src/Stream.php index d3bd78d..39fef03 100644 --- a/src/Stream.php +++ b/src/Stream.php @@ -260,8 +260,26 @@ 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 (string $type, string $message, string $file, int $line) use (&$exception): bool { + $exception = new \RuntimeException('Unable to read from stream: ' . $message); + + return true; + }); + + $contents = ''; + + try { + $contents = \stream_get_contents($this->stream); + } catch (\Throwable $e) { + $exception = new \RuntimeException('Unable to read from stream: ' . $e->getMessage(), 0, $e); + } + + \restore_error_handler(); + + if ($exception) { + throw $exception; } return $contents;