Skip to content

Instantly share code, notes, and snippets.

@xwero
Created June 13, 2011 05:23
Show Gist options
  • Save xwero/1022345 to your computer and use it in GitHub Desktop.
Save xwero/1022345 to your computer and use it in GitHub Desktop.
Throw Kohana exception if json function returns nothing
<?php
/**
* Throw Kohana exception if json function returns nothing
*
* @example
* $en = json_encode("\xB1\x31");
*
* check_json_error($en);
*
* $de = json_decode("{'Organization': 'Kohana'}");
*
* check_json_error($de);
*
* @param mixed $json_result
*/
function check_json_error($json_result)
{
if($json_result == NULL OR $json_result == 'null')
{
$error = '';
switch(json_last_error())
{
case JSON_ERROR_DEPTH:
$error = 'Maximum stack depth exceeded';
break;
case JSON_ERROR_CTRL_CHAR:
$error = 'Unexpected control character found';
break;
case JSON_ERROR_STATE_MISMATCH:
$error = 'Invalid or malformed JSON';
break;
case JSON_ERROR_SYNTAX:
$error = 'Syntax error';
break;
case JSON_ERROR_UTF8:
$error = 'Malformed UTF-8 characters, possibly incorrectly encoded';
}
if ($error)
{
throw new Kohana_Exception('JSON error: :error', array(':error' => $error));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment