Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

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
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi
SerpApi logo

SerpApi

Access real-time search engine results through a simple API—no more scraping headaches! Use it for AI applications, SEO tools, product research, travel information, and more

SerpApi
Lucky Media logo

Lucky Media

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

Lucky Media
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
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
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Tinkerwell logo

Tinkerwell

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

Tinkerwell
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
Shift logo

Shift

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

Shift
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
Laravel Cloud logo

Laravel Cloud

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

Laravel Cloud

The latest

View all →
Laravel ClickHouse: A Full-Featured ClickHouse Driver for Laravel image

Laravel ClickHouse: A Full-Featured ClickHouse Driver for Laravel

Read article
Laravel Installer Now Returns JSON When Running Inside an AI Agent image

Laravel Installer Now Returns JSON When Running Inside an AI Agent

Read article
Queue-Wide Inspection Methods in Laravel 13.8.0 image

Queue-Wide Inspection Methods in Laravel 13.8.0

Read article
Verifiable Audit Logging with Laravel Chronicle image

Verifiable Audit Logging with Laravel Chronicle

Read article
Ship AI with Laravel: Search Entire PDFs with Zero Search Logic image

Ship AI with Laravel: Search Entire PDFs with Zero Search Logic

Read article
Personalized Content Delivery System: Building an AI-powered recommendation engine with Laravel and MongoDB image

Personalized Content Delivery System: Building an AI-powered recommendation engine with Laravel and MongoDB

Read article