21 lines
622 B
PHP
21 lines
622 B
PHP
<?php
|
|
namespace nulib\php\json;
|
|
|
|
use RuntimeException;
|
|
|
|
class JsonException extends RuntimeException {
|
|
static final function json_last_error(?string $prefix=null): ?self {
|
|
$json_last_error = json_last_error();
|
|
if ($json_last_error === JSON_ERROR_NONE) return null;
|
|
$message = json_last_error_msg()." ($json_last_error)";
|
|
if ($prefix) $message = "$prefix: $message";
|
|
return new static($message);
|
|
}
|
|
|
|
static final function ensure_json_value($value, ?string $prefix=null) {
|
|
$exception = self::json_last_error($prefix);
|
|
if ($exception === null) return $value;
|
|
else throw $exception;
|
|
}
|
|
}
|