PHP 7.3: A Look at JSON Error Handling

Published on by

PHP 7.3: A Look at JSON Error Handling image

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.

Laravel Forge logo

Laravel Forge

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

Laravel Forge
Tinkerwell logo

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 logo

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 logo

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 logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

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 logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

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 logo

Rector

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

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Add Comments to your Laravel Application with the Commenter Package image

Add Comments to your Laravel Application with the Commenter Package

Read article
Laravel Advanced String Package image

Laravel Advanced String Package

Read article
Take the Annual State of Laravel 2024 Survey image

Take the Annual State of Laravel 2024 Survey

Read article
Upload Files Using Filepond in Livewire Components image

Upload Files Using Filepond in Livewire Components

Read article
The Best Laravel Tutorials and Resources for Developers image

The Best Laravel Tutorials and Resources for Developers

Read article
Introducing Built with Laravel image

Introducing Built with Laravel

Read article