mailgun / mailgun-php

Mailgun's Official SDK for PHP
http://www.mailgun.com
MIT License
1.09k stars 314 forks source link

Bug: Proper json_last_error() handling with try catch #882

Closed Pilskalns closed 9 months ago

Pilskalns commented 9 months ago

So, the last release introduces more strict JSON syntax check.

There is an inherent/global issue with how json_last_error() works. In short, the returned error code can be a false positive. It does not reset after a successful encode or decode call. It changes only when there is a new error code.

At the issue core is the following sequence, which gives unintuitive results:

<?php
json_decode("\00invalid json");
var_dump(json_last_error());

json_decode("[]", true, 512, JSON_THROW_ON_ERROR);
var_dump(json_last_error());

Both var dumps would return an error code. You can read about the issue source over this thread: https://github.com/php/php-src/issues/10166

While in isolation this works ok, in the integration it becomes unreliable if, in the same call/request, there was another error code thrown (i.e. to check if a string is a json). I'm preparing a PR that uses try-catch to handle the error properly.