[core] add custom error messages for stdlib_ex, and a test
This commit is contained in:
parent
51afc014a2
commit
92577d355f
2 changed files with 40 additions and 5 deletions
|
@ -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
|
||||
|
|
27
core/tests/StdLibExTest.php
Normal file
27
core/tests/StdLibExTest.php
Normal file
|
@ -0,0 +1,27 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Shimmie2;
|
||||
|
||||
class StdLibExTest extends ShimmiePHPUnitTestCase
|
||||
{
|
||||
public function testJsonEncodeOk(): void
|
||||
{
|
||||
$this->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()
|
||||
);
|
||||
}
|
||||
}
|
Reference in a new issue