PHP 7.3: A Look at JSON Error Handling

Published on by

One of the new features coming to PHP 7.3 is better error handling for json_encode() and json_decode(). The RFC was unanimously accepted by a 23 to 0 vote. Let’s take a look at how we handle JSON errors in <= PHP 7.2, and the new improvements coming in PHP 7.3.

Background

In the current stable, PHP v7.2, if you want to determine if JSON is invalid, you have to use the json_last_error() function to verify:

>>> json_decode("{");
=> null
>>> json_last_error();
=> 4
>>> json_last_error() === JSON_ERROR_NONE
=> false
>>> json_last_error_msg()
=> "Syntax error"

For example, in the Laravel Illuminate\Encryption\Encrypter class here’s a check to make sure calling json_encode() doesn’t result in an error:

// Once we get the encrypted value we'll go ahead and base64_encode the input
// vector and create the MAC for the encrypted value so we can then verify
// its authenticity. Then, we'll JSON the data into the "payload" array.
$json = json_encode(compact('iv', 'value', 'mac'));
 
if (json_last_error() !== JSON_ERROR_NONE) {
throw new EncryptException('Could not encrypt the data.');
}
 
return base64_encode($json);

We can at least determine if JSON encoding/decoding had an error, but it’s a little clunky compared to throwing an exception, which packages the error code and message neatly together.

Although you have to opt-in, v7.3 has an excellent way of allowing you to catch and handle JSON exceptions—let’s check out the new flag we can use!

The Throw on Error Flag in PHP 7.3

With the new option flag JSON_THROW_ON_ERROR it’s possible to rewrite this block of code with a try/catch. Maybe some something like the following:

use JsonException;
 
try {
$json = json_encode(compact('iv', 'value', 'mac'), JSON_THROW_ON_ERROR);
return base64_encode($json);
} catch (JsonException $e) {
throw new EncryptException('Could not encrypt the data.', 0, $e);
}

I think this new style is especially useful for userland code when you receive some JSON data and instead of digging around for json_last_error() and the matching flag, your JSON encoding and decoding can take advantage of the error handler.

The json_decode() function has a few more arguments, and will look something like the following in PHP 7.3 if you want to take advantage of error handling:

use JsonException;
 
try {
return json_decode($jsonString, $assoc = true, $depth = 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
// Handle the JSON Exception
}
 
// Or even just let it bubble up...
 
/**
* Decode a JSON string into an array
*
* @return array
* @throws JsonException
*/
function decode($jsonString) {
return json_decode($jsonString, $assoc = true, $depth = 512, JSON_THROW_ON_ERROR);
}

Getting the Error Code and Message

Previously you retrieve the JSON error code and message using the following functions:

// Error code
json_last_error();
 
// Human-friendly message
json_last_error_msg();

If you use the new JSON_THROW_ON_ERROR flag, here’s how you’ll get the code and message:

try {
return json_decode($jsonString, $assoc = true, $depth = 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
$e->getMessage(); // like json_last_error_msg()
$e->getCode(); // like json_last_error()
}

See the base Exception class for more API details, the JsonException exception is a subclass of Exception.

JSON’s Default Behavior in PHP 7.3

When upgrading to PHP 7.3, your code will be backward compatible on day one and continue to work as expected.

PHP’s default json_encode|decode() behavior hasn’t changed, the throw on error RFC adds a new option and exception class.

Learn More

You can learn all about the most prominent features coming to PHP 7.3 in our post announcing the PHP 7.3 Alpha 1 release last week. Also, read through the RFC for JSON_THROW_ON_ERROR for full details on the proposal coming to PHP 7.3.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Filed in:
Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Tinkerwell

Version 4 of Tinkerwell is available now. Get the most popular PHP scratchpad with all its new features and simplify your development workflow today.

Visit Tinkerwell

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce

LaraJobs

The official Laravel job board

LaraJobs

Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes. Available with Vue and Livewire stacks.

Larafast: Laravel SaaS Starter Kit

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →

Backpack turns 8 years old, celebrates with 40% discount

Read article

Create a DateTime from a Timestamp With this New Method Coming to PHP 8.4

Read article

Neovim Plugin to for Navigating Laravel and Livewire Components

Read article

Laravel Herd v1.7 is out with updates to the dump UI

Read article

Share Error Package for Laravel's New Exception Page

Read article

Sentry and Laravel announce a new partnership

Read article