Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
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
  • Loading branch information
nicolas-grekas committed Jun 28, 2019
2 parents 8477f2b + 9c76790 commit 2bab37d
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/Symfony/Component/Serializer/Encoder/JsonEncode.php
Expand Up @@ -35,14 +35,19 @@ public function __construct($bitmask = 0)
public function encode($data, $format, array $context = [])
{
$context = $this->resolveContext($context);
$options = $context['json_encode_options'];

$encodedJson = json_encode($data, $context['json_encode_options']);
try {
$encodedJson = json_encode($data, $options);
} catch (\JsonException $e) {
throw new NotEncodableValueException($e->getMessage(), 0, $e);
}

if (\PHP_VERSION_ID >= 70300 && (JSON_THROW_ON_ERROR & $context['json_encode_options'])) {
if (\PHP_VERSION_ID >= 70300 && (JSON_THROW_ON_ERROR & $options)) {
return $encodedJson;
}

if (JSON_ERROR_NONE !== json_last_error() && (false === $encodedJson || !($context['json_encode_options'] & JSON_PARTIAL_OUTPUT_ON_ERROR))) {
if (JSON_ERROR_NONE !== json_last_error() && (false === $encodedJson || !($options & JSON_PARTIAL_OUTPUT_ON_ERROR))) {
throw new NotEncodableValueException(json_last_error_msg());
}

Expand Down

0 comments on commit 2bab37d

Please sign in to comment.