PHP JSON decode with actionable errors
PHP
<?php
function decode_json(string $raw): mixed
{
try {
return json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
$snippet = substr($raw, 0, 120);
throw new InvalidArgumentException(
'Invalid JSON: ' . $e->getMessage() . ' near: ' . $snippet,
(int) $e->getCode(),
$e
);
}
}