Join the Mastering Laravel community to level up your skills and get trusted advice

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.

image
Battle Ready Laravel

The ultimate guide to auditing, testing, fixing and improving your Laravel applications so you can build better apps faster and with more confidence.

Visit Battle Ready Laravel
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
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
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
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Join the Mastering Laravel community logo

Join the Mastering Laravel community

Connect with experienced developers in a friendly, noise-free environment. Get insights, share ideas, and find support for your coding challenges. Join us today and elevate your Laravel skills!

Join the Mastering Laravel community
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
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 Multi-tenant 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

The latest

View all →
Auto-translate Application Strings with Laratext image

Auto-translate Application Strings with Laratext

Read article
Simplify Factory Associations with Laravel's UseFactory Attribute image

Simplify Factory Associations with Laravel's UseFactory Attribute

Read article
Improved Installation and Frontend Hooks in Laravel Echo 2.1 image

Improved Installation and Frontend Hooks in Laravel Echo 2.1

Read article
Filter Model Attributes with Laravel's New except() Method image

Filter Model Attributes with Laravel's New except() Method

Read article
Arr::from() Method in Laravel 12.14 image

Arr::from() Method in Laravel 12.14

Read article
Streamline API Resources with Laravel's Fluent Methods image

Streamline API Resources with Laravel's Fluent Methods

Read article