[core] add custom error messages for stdlib_ex, and a test

This commit is contained in:
Shish
2024-02-05 13:25:18 +00:00
parent 51afc014a2
commit 92577d355f
2 changed files with 40 additions and 5 deletions

View File

@@ -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