Check if the last json operation returned an error and convert it to an exception.
Designed as an internal method called after any json operation,
but there's no reason it can't be called after a straight call to the php json_* functions.

@return void
766821
public static function checkLastError()
    {
        $error = json_last_error();

        if ($error == JSON_ERROR_NONE) {
            return;
        }

        $message = json_last_error_msg();

        throw new JsonException("JSON Error: " . $message, $error);
    }
402192
public function isValid($json=null) {
			if (empty($json) || ctype_space($json)) return false;
			json_decode($json);
			return (json_last_error() === JSON_ERROR_NONE);
		}
942780
protected function jsonValidator($data = null):bool
    {
        if (! empty($data)) {
            @json_decode($data);

            return json_last_error() === JSON_ERROR_NONE;
        }

        return false;
    }
97431
public static function checkError()
    {
        switch (json_last_error()) {
            case JSON_ERROR_NONE:
                $msg = null;
                break;
            case JSON_ERROR_DEPTH:
                $msg = 'Maximum stack depth exceeded';
                break;
            case JSON_ERROR_STATE_MISMATCH:
                $msg = 'Underflow or the modes mismatch';
                break;
            case JSON_ERROR_CTRL_CHAR:
                $msg = 'Unexpected control character found';
                break;
            case JSON_ERROR_SYNTAX:
                $msg = 'Syntax error, malformed JSON';
                break;
            case JSON_ERROR_UTF8:
                $msg = 'Malformed UTF-8 characters, possibly incorrectly encoded';
                break;
            default:
                $msg = 'Unknown error';
                break;
        }
        return $msg;
    }
1102889
public function seeResponseIsJson()
    {
        $responseContent = $this->connectionModule->_getResponseContent();
        \PHPUnit\Framework\Assert::assertNotEquals('', $responseContent, 'response is empty');
        json_decode($responseContent);
        $errorCode = json_last_error();
        $errorMessage = json_last_error_msg();
        \PHPUnit\Framework\Assert::assertEquals(
            JSON_ERROR_NONE,
            $errorCode,
            sprintf(
                "Invalid json: %s. System message: %s.",
                $responseContent,
                $errorMessage
            )
        );
    }
205779
private function phpExceptionHandler(): Closure
    {
        return static function (Throwable $ex): void {
            $base_path = dirname(__DIR__);
            $trace     = $ex->getMessage() . PHP_EOL . $ex->getTraceAsString();
            $trace     = str_replace($base_path, '…', $trace);

            while (ob_get_level() > 0) {
                ob_end_clean();
            }

            echo '<html lang="en"><head><title>Error</title><meta charset="UTF-8"></head><body><pre>' . $trace . '</pre></body></html>';
        };
    }
697997
public function _handleFailure()
    {
        if($this->isEnabled(self::TYPE_FAILURE))
        {
            $error = error_get_last();

            // Make sure error happened after we started handling them
            if ($error && md5(serialize($error)) !== $this->__last_unhandled_error)
            {
                $level = $error['type'];

                if ($this->getErrorReporting() & $level)
                {
                    $exception = new ExceptionFailure(
                        $error['message'], HttpResponse::INTERNAL_SERVER_ERROR, $level, $error['file'], $error['line']
                    );

                    $this->handleException($exception);
                }
            }
        }
    }
1311952
private static function getLastJsonError()
    {
        if (function_exists('json_last_error_msg')) {
            return json_last_error_msg();
        }
        static $errors = array(
            JSON_ERROR_NONE           => null,
            JSON_ERROR_DEPTH          => 'Maximum stack depth exceeded',
            JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch',
            JSON_ERROR_CTRL_CHAR      => 'Unexpected control character found',
            JSON_ERROR_SYNTAX         => 'Syntax error, malformed JSON',
            JSON_ERROR_UTF8           => 'Malformed UTF-8 characters, possibly incorrectly encoded',
        );
        $error = json_last_error();

        return array_key_exists($error, $errors)
            ? $errors[$error]
            : sprintf('Unknown error (%s)', $error);
    }
993296
public function json()
    {
        $json = json_decode($this->getBody(), true);
        if ($json === null) {
            throw new RuntimeException(sprintf(
                "Can't decode response as JSON: %s",
                function_exists('json_last_error_msg')?
                    json_last_error_msg():
                    'Error code '.json_last_error()
            ));
        }
        return $json;
    }
927309
protected function handleJsonError($error)
    {
        switch ($error) {
            case JSON_ERROR_NONE: break; // handle nothing
            case JSON_ERROR_DEPTH: throw new Exception("Maximum stack depth exceeded");
            case JSON_ERROR_STATE_MISMATCH: throw new Exception("Underflow or the modes mismatch");
            case JSON_ERROR_CTRL_CHAR: throw new Exception("Unexpected control character found");
            case JSON_ERROR_SYNTAX: throw new Exception("Syntax error, malformed JSON");
            case JSON_ERROR_UTF8: throw new Exception("Malformed UTF-8 characters, possibly incorrectly encoded");
            default: throw new Exception("Unknown error");
        }
    }
1371479
public function validateCall(): void
    {

        if (! in_array($this->method, ['get', 'post', 'put', 'patch', 'delete']))
            throw new Exception('Invalid HTTP method used');

        if (trim($this->endpoint) === '')
            throw new Exception('Empty endpoint used');

        // Enfore a version specification unless this is a 'meta' call.
        if (trim($this->version) === '' && ! (in_array('meta', $this->tags())))
            throw new Exception('Version is empty');
    }
684472
private static function checkForError(array $jsonResult)
    {
        if (isset($jsonResult[ 'success' ]) && true === (bool) $jsonResult[ 'success' ]) {
            return false;
        }

        if (isset($jsonResult[ 'error' ])) {
            $error = $jsonResult[ 'error' ];
            throw new WSException(
                $error[ 'message' ],
                $error[ 'code' ]
            );
        }

        // This should never happen
        throw new WSException('Unknown error');
    }
441310
public static function error($json)
    {
        $fields = Deserialize::_fromJson($json);

        $result = new Api\Error();
        $result->setCode($fields->code);
        $result->setText($fields->text);

        return $result;
    }
559503
public function hasErrors() {
    foreach ($this->jsonArray as $error) {
      if ($error['type'] != self::OK)
        return TRUE;
    }
    return FALSE;
  }
1159823
private function decodeJson( $json ) {
		$error = $errorMsg = null;
		$return = json_decode( $json );
		if ( $return === null && trim( $json ) !== 'null' ) {
			$error = json_last_error();
			$errorMsg = json_last_error_msg();
		} elseif ( !$return || !is_object( $return ) ) {
			$error = 128;
			$errorMsg = 'Response must be an object';
		}

		if ( $error ) {
			$this->logger->error(
				'Failed to decode server response as JSON: {message}',
				[
					'response' => $json,
					'code' => json_last_error(),
					'message' => json_last_error_msg(),
				]
			);
			throw new Exception( 'Decoding server response failed: ' . json_last_error_msg()
				. " (Raw response: $json)" );
		}
		return $return;
	}
883309
final public static function fromLastError()
    {
        $error = error_get_last();
        if ($error !== null) {
            return new ErrorException($error['message'], 0, $error['type'], $error['file'], $error['line']);
        }
    }
80533
public function onRequestTerminate() 
  {
    // lets see if there were unhandled fatal errors
    $lasterror=error_get_last();
    if(!is_null($lasterror)){
      if($lasterror['type'] & (E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR)){
        // fatal error occured
        // increase memory limit so we we can at least complete our error handling (in case it was Allowed memory size exhausted)
        // (adding 1MB, unless already unlimited)
        $memlim=Web2All_PHP_INI::getBytes(ini_get('memory_limit'));
        if($memlim!=-1){
          ini_set('memory_limit',$memlim+1000000);
        }
        // then add this error to the observers
        $error = Web2All_Manager_Error::getInstance();
        $exception = new Web2All_Manager_TriggerException($lasterror['type'], $lasterror['message'], $lasterror['file'], $lasterror['line'], array());
        if ($error) {
          $error->setState($exception,$lasterror['type']);
        }
      }
    }
  }