Skip to content

Commit bbb5a23

Browse files
committed
Catch all json-encode errors
1 parent ad19b1d commit bbb5a23

File tree

3 files changed

+13
-7
lines changed

3 files changed

+13
-7
lines changed

docs/document.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -165,10 +165,10 @@ Removes empty objects and arrays from the data. If *$order* is true and a schema
165165
function re-orders the data using the schema content.
166166

167167
### toJson
168-
string **toJson** ( bool `$pretty` )
168+
?string **toJson** ( bool `$pretty` )
169169

170170
Returns a json-encoded string of `$document->data`. If *$pretty* is true, the output will be
171-
pretty-printed.
171+
pretty-printed. Returns null on failure with the error in `$document->getError()`.
172172

173173
*Back to:* [Contents](#contents)
174174

docs/formatter.md

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,6 @@ $data = $formatter->prune($data);
9999
```
100100

101101
### toJson
102-
mixed **toJson** ( mixed `$data`, bool `$pretty` )
102+
string **toJson** ( mixed `$data`, int `$options` )
103103

104-
Returns a json-encoded string of *$data*. Forward-slashes are not escaped and UTF-8 characters are
105-
not encoded. If *$pretty* is true, the output will be *pretty-printed*.
104+
Returns a json-encoded string of *$data*. Throws a *RuntimeException* on failure.

src/BaseDocument.php

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,12 +75,19 @@ public function getError(): string
7575
return $this->error;
7676
}
7777

78-
public function toJson(bool $pretty): string
78+
public function toJson(bool $pretty): ?string
7979
{
8080
$options = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
8181
$options |= $pretty ? JSON_PRETTY_PRINT : 0;
8282

83-
return $this->formatter->toJson($this->data, $options);
83+
try {
84+
$result = $this->formatter->toJson($this->data, $options);
85+
} catch (\RuntimeException $e) {
86+
$result = null;
87+
$this->error = $e->getMessage();
88+
}
89+
90+
return $result;
8491
}
8592

8693
public function validate(): bool

0 commit comments

Comments
 (0)