mirror of
https://github.com/Seldaek/monolog.git
synced 2025-08-02 19:27:37 +02:00
Avoid throwing an exception when the toString fails (#1868)
This commit is contained in:
@@ -210,8 +210,14 @@ class NormalizerFormatter implements FormatterInterface
|
|||||||
$accessor = new \ArrayObject($data);
|
$accessor = new \ArrayObject($data);
|
||||||
$value = (string) $accessor['__PHP_Incomplete_Class_Name'];
|
$value = (string) $accessor['__PHP_Incomplete_Class_Name'];
|
||||||
} elseif (method_exists($data, '__toString')) {
|
} elseif (method_exists($data, '__toString')) {
|
||||||
|
try {
|
||||||
/** @var string $value */
|
/** @var string $value */
|
||||||
$value = $data->__toString();
|
$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 {
|
} else {
|
||||||
// the rest is normalized by json encoding and decoding it
|
// the rest is normalized by json encoding and decoding it
|
||||||
/** @var null|scalar|array<mixed[]|scalar|null> $value */
|
/** @var null|scalar|array<mixed[]|scalar|null> $value */
|
||||||
|
@@ -131,11 +131,25 @@ class NormalizerFormatterTest extends TestCase
|
|||||||
public function testFormatToStringExceptionHandle()
|
public function testFormatToStringExceptionHandle()
|
||||||
{
|
{
|
||||||
$formatter = new NormalizerFormatter('Y-m-d');
|
$formatter = new NormalizerFormatter('Y-m-d');
|
||||||
$this->expectException('RuntimeException');
|
$formatted = $formatter->format($this->getRecord(context: [
|
||||||
$this->expectExceptionMessage('Could not convert to string');
|
|
||||||
$formatter->format($this->getRecord(context: [
|
|
||||||
'myObject' => new TestToStringError(),
|
'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()
|
public function testBatchFormat()
|
||||||
|
Reference in New Issue
Block a user