Skip to content

Commit 8e77282

Browse files
authored
Merge pull request #3465 from iliaal/fix/json-error-renderer-invalid-utf8
Substitute invalid UTF-8 in JSON error renderer output
2 parents df489a9 + 9f5842e commit 8e77282

3 files changed

Lines changed: 23 additions & 1 deletion

File tree

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
## [Unreleased]
44

55
### Fixed
6+
- Substitute invalid UTF-8 in JSON error renderer output (#811)
67

78
### Added
89

Slim/Error/Renderers/JsonErrorRenderer.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
use function get_class;
1717
use function json_encode;
1818

19+
use const JSON_INVALID_UTF8_SUBSTITUTE;
1920
use const JSON_PRETTY_PRINT;
2021
use const JSON_UNESCAPED_SLASHES;
2122

@@ -35,7 +36,10 @@ public function __invoke(Throwable $exception, bool $displayErrorDetails): strin
3536
} while ($exception = $exception->getPrevious());
3637
}
3738

38-
return (string) json_encode($error, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
39+
return (string) json_encode(
40+
$error,
41+
JSON_INVALID_UTF8_SUBSTITUTE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
42+
);
3943
}
4044

4145
/**

tests/Error/AbstractErrorRendererTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,23 @@ public function testJSONErrorRendererDoesNotDisplayErrorDetails()
163163
$this->assertSame($output, json_encode(['message' => 'Slim Application Error']));
164164
}
165165

166+
public function testJSONErrorRendererSubstitutesInvalidUtf8()
167+
{
168+
$exception = new Exception("Invalid \xB1\x31 UTF-8 sequence");
169+
170+
$renderer = new JsonErrorRenderer();
171+
$output = $renderer->__invoke($exception, true);
172+
173+
$this->assertNotSame('', $output);
174+
$decoded = json_decode($output, true);
175+
$this->assertIsArray($decoded);
176+
$this->assertSame('Slim Application Error', $decoded['message']);
177+
$this->assertSame(
178+
"Invalid \u{FFFD}1 UTF-8 sequence",
179+
$decoded['exception'][0]['message']
180+
);
181+
}
182+
166183
public function testJSONErrorRendererDisplaysPreviousError()
167184
{
168185
$previousException = new Exception('Oh no!');

0 commit comments

Comments
 (0)