Run
Run

Reputation: 57176

How to throw an error message with json_decode?

How can I throw an error message with json_decode?

For instance,

$error = array(
    "key_name" => "Keyname - empty!",
    "pub_name" => "Pubname - empty!",
    "path" => "path - empty!"
);

$json = json_encode($error);
$object = json_decode($json);
print_r($object->keyname);

I get,

Notice: Undefined property: stdClass::$key_namex in C:.... on line 32

keyname does not exist actually, so I wonder if I can check it with the if condition,

if(!$object->keyname) { .... }

is it possible?

and sometimes I there are no error content,

$error = array(
);

$json = json_encode($error);
$object = json_decode($json);
print_r($object->key_name);

so I thought of throwing an error before proceeding to the codes that follows,

if($object == '') {...}

is it possible?

Upvotes: 0

Views: 1978

Answers (3)

Raymond Nijland
Raymond Nijland

Reputation: 11602

You should be able to throw and catch json decode errors like this. You could extend this also to handle encode.

class Json {

   public static function decode($jsonString) {  
       if ((string)$jsonString !== $jsonString) {  // faster !is_string check
          throw new Exception('input should be a string');
       }

       $decodedString = json_decode($jsonString)

       if ((unset)$decodedString === $decodedString) { // faster is_null check, why NULL check because json_decode return NULL with failure. 
           $errorArray = error_get_last(); // fetch last error this should be the error of the json decode or it could be a date timezone error if you didn't set it correctly   

           throw new Exception($errorArray['message']); 
       }
       return $decodedString;
   }
}



try {
   Json::decode("ERROR");
} catch (Exception $e) {  }

Upvotes: 2

Homer6
Homer6

Reputation: 15159

You should prefer to use property_exists() over isset().

As opposed with isset(), property_exists() returns TRUE even if the property has the value NULL.

if( property_exists($object, 'keyname') ){ 
   throw new Exception( 'Object key does not exist.' ); //I prefer this method
   //or
   trigger_error( 'Object key does not exist.', E_USER_ERROR );
}

Incidentally, the same pattern should be used with arrays (array_key_exists is preferred over isset for that same reason).

Upvotes: 3

dev-null-dweller
dev-null-dweller

Reputation: 29462

keyname does not exist actually, so I wonder if I can check it with the if condition,

You can, but with noo plain if but using isset:

if (isset($object->keyname)) { 

}

Just as you would for any variable / array offset.

As for checking if object has any properties, either use second argument to json_decode (to have associative array) or cast it to array and check if it is empty:

$obj = json_decode('{}');
if (!empty((array)$obj)) {
}

Upvotes: 1

Related Questions