Skip to content

Commit

Permalink
Avoid throwing an exception when the toString fails (#1868)
Browse files Browse the repository at this point in the history
  • Loading branch information
VincentLanglet committed Apr 12, 2024
1 parent a693dc2 commit c4ba76a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
10 changes: 8 additions & 2 deletions src/Monolog/Formatter/NormalizerFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -210,8 +210,14 @@ protected function normalize(mixed $data, int $depth = 0): mixed
$accessor = new \ArrayObject($data);
$value = (string) $accessor['__PHP_Incomplete_Class_Name'];
} elseif (method_exists($data, '__toString')) {
/** @var string $value */
$value = $data->__toString();
try {
/** @var string $value */
$value = $data->__toString();
} catch (\Throwable) {
// if the toString method is failing, use the default behavior
/** @var null|scalar|array<mixed[]|scalar|null> $value */
$value = json_decode($this->toJson($data, true), true);
}
} else {
// the rest is normalized by json encoding and decoding it
/** @var null|scalar|array<mixed[]|scalar|null> $value */
Expand Down
20 changes: 17 additions & 3 deletions tests/Monolog/Formatter/NormalizerFormatterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,11 +131,25 @@ public function testFormatSoapFaultException()
public function testFormatToStringExceptionHandle()
{
$formatter = new NormalizerFormatter('Y-m-d');
$this->expectException('RuntimeException');
$this->expectExceptionMessage('Could not convert to string');
$formatter->format($this->getRecord(context: [
$formatted = $formatter->format($this->getRecord(context: [
'myObject' => new TestToStringError(),
]));
$this->assertEquals(
[
'level_name' => Level::Warning->getName(),
'level' => Level::Warning->value,
'channel' => 'test',
'message' => 'test',
'context' => [
'myObject' => [
TestToStringError::class => [],
],
],
'datetime' => date('Y-m-d'),
'extra' => [],
],
$formatted
);
}

public function testBatchFormat()
Expand Down

0 comments on commit c4ba76a

Please sign in to comment.