diff --git a/core/stdlib_ex.php b/core/stdlib_ex.php index 0122d3fd..f2197f8f 100644 --- a/core/stdlib_ex.php +++ b/core/stdlib_ex.php @@ -5,10 +5,14 @@ * @param T|false $x * @return T */ -function false_throws(mixed $x): mixed +function false_throws(mixed $x, ?callable $errorgen=null): mixed { if($x === false) { - throw new \Exception("Unexpected false"); + $msg = "Unexpected false"; + if($errorgen) { + $msg = $errorgen(); + } + throw new \Exception($msg); } return $x; } @@ -18,10 +22,14 @@ function false_throws(mixed $x): mixed * @param T|null $x * @return T */ -function null_throws(mixed $x): mixed +function null_throws(mixed $x, ?callable $errorgen=null): mixed { if($x === null) { - throw new \Exception("Unexpected null"); + $msg = "Unexpected null"; + if($errorgen) { + $msg = $errorgen(); + } + throw new \Exception($msg); } return $x; } @@ -31,7 +39,7 @@ function null_throws(mixed $x): mixed */ function json_encode_ex(mixed $value, int|null $flags = 0, int $depth = 512): string { - return false_throws(json_encode($value, $flags, $depth)); + return false_throws(json_encode($value, $flags, $depth), "json_last_error_msg"); } function strtotime_ex(string $time, int|null $now = null): int diff --git a/core/tests/StdLibExTest.php b/core/tests/StdLibExTest.php new file mode 100644 index 00000000..4b2ee485 --- /dev/null +++ b/core/tests/StdLibExTest.php @@ -0,0 +1,27 @@ +assertEquals( + '{"a":1,"b":2,"c":3,"d":4,"e":5}', + json_encode_ex(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5]) + ); + } + + public function testJsonEncodeError(): void + { + $e = $this->assertException(\Exception::class, function() { + json_encode_ex("\xB1\x31"); + }); + $this->assertEquals( + "Malformed UTF-8 characters, possibly incorrectly encoded", + $e->getMessage() + ); + } +}