Wrap json_encode() to throw error when the value being encoded fails

This commit is contained in:
Zach Borboa
2018-08-01 23:45:57 -07:00
parent 6226ca0dd0
commit 082f7389e3
+32 -9
View File
@@ -143,15 +143,7 @@ class Curl
// Return JSON-encoded string when the request's content-type is JSON.
if (isset($this->headers['Content-Type']) &&
preg_match($this->jsonPattern, $this->headers['Content-Type'])) {
$data = json_encode($data);
if (!(json_last_error() === JSON_ERROR_NONE)) {
if (function_exists('json_last_error_msg')) {
$error_message = 'json_encode error: ' . json_last_error_msg();
} else {
$error_message = 'json_encode error';
}
throw new \ErrorException($error_message);
}
$data = \Curl\json_encode($data);
} else {
// Manually build a single-dimensional array from a multi-dimensional array as using curl_setopt($ch,
// CURLOPT_POSTFIELDS, $data) doesn't correctly handle multi-dimensional arrays when files are
@@ -1761,3 +1753,34 @@ function createHeaderCallback($header_callback_data) {
return strlen($header);
};
}
/**
* Json Encode
*
* Wrap json_encode() to throw error when the value being encoded fails.
*
* @param $value
* @param $options
* @param $depth
*
* @return string
* @throws \ErrorException
*/
function json_encode($value, $options = 0, $depth = 512) {
// Make compatible with PHP version both before and after 5.5.0. PHP 5.5.0 added the $depth parameter.
$gte_v550 = version_compare(PHP_VERSION, '5.5.0') >= 0;
if ($gte_v550) {
$value = \json_encode($value, $options, $depth);
} else {
$value = \json_encode($value, $options);
}
if (!(json_last_error() === JSON_ERROR_NONE)) {
if (function_exists('json_last_error_msg')) {
$error_message = 'json_encode error: ' . json_last_error_msg();
} else {
$error_message = 'json_encode error';
}
throw new \ErrorException($error_message);
}
return $value;
}