Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 2bab37d

Browse files
bug #32206 Catch JsonException and rethrow in JsonEncode (phil-davis)
This PR was merged into the 3.4 branch. Discussion ---------- Catch JsonException and rethrow in JsonEncode | Q | A | ------------- | --- | Branch? | 3.4 | Bug fix? | yes | New feature? | no | BC breaks? | no | Deprecations? | no | Tests pass? | yes | Fixed tickets | adjustment to implementation of previous PRs for issue #31447 | License | MIT | Doc PR | not applicable PR #31860 provided handling of PHP 7.3 `JSON_THROW_ON_ERROR` behavior in the various `JsonEncode` and related classes/methods. PR #31869 adjusted that. In particular, it adjusted ` src/Symfony/Component/Serializer/Encoder/JsonDecode.php` so that it catches any `JsonException` and re-throws it as `NotEncodableValueException`. That preserves the previous behavior of `JsonDecode:decode` - it always throws `NotEncodableValueException` when something goes wrong. IMO `JsonEncode:encode` needs the same logic. At the moment, if a caller specifies `JSON_THROW_ON_ERROR` then the method can throw `JsonException`, but actually the "standard" for `JsonEncode:encode` is that it throws `NotEncodableValueException` Adjust `JsonEncode:encode` to catch `JsonException` and rethrow it as `NotEncodableValueException` Commits ------- 9c76790 Catch JsonException and rethrow in JsonEncode
2 parents 8477f2b + 9c76790 commit 2bab37d

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

src/Symfony/Component/Serializer/Encoder/JsonEncode.php

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,14 +35,19 @@ public function __construct($bitmask = 0)
3535
public function encode($data, $format, array $context = [])
3636
{
3737
$context = $this->resolveContext($context);
38+
$options = $context['json_encode_options'];
3839

39-
$encodedJson = json_encode($data, $context['json_encode_options']);
40+
try {
41+
$encodedJson = json_encode($data, $options);
42+
} catch (\JsonException $e) {
43+
throw new NotEncodableValueException($e->getMessage(), 0, $e);
44+
}
4045

41-
if (\PHP_VERSION_ID >= 70300 && (JSON_THROW_ON_ERROR & $context['json_encode_options'])) {
46+
if (\PHP_VERSION_ID >= 70300 && (JSON_THROW_ON_ERROR & $options)) {
4247
return $encodedJson;
4348
}
4449

45-
if (JSON_ERROR_NONE !== json_last_error() && (false === $encodedJson || !($context['json_encode_options'] & JSON_PARTIAL_OUTPUT_ON_ERROR))) {
50+
if (JSON_ERROR_NONE !== json_last_error() && (false === $encodedJson || !($options & JSON_PARTIAL_OUTPUT_ON_ERROR))) {
4651
throw new NotEncodableValueException(json_last_error_msg());
4752
}
4853

0 commit comments

Comments
 (0)