Can you throw an array instead of a string as an exception in php?
Asked Answered
G

4

28

I want to throw an array as an exception in php, instead of a string. Is it possible to do this if you define your own class that extends the Exception class?

For example throw new CustomException('string', $options = array('params'));

Greenockite answered 22/7, 2011 at 23:26 Comment(1)
I think I might be a little bit sick. Interesting question, though.Necking
C
56

Sure. It will just be up to your error handling code to be aware of, and make use of the array property appropriately. You can define your custom exception class's constructor to take any parameters you want, and then just be sure to call the base class's constructor from within the constructor definition, eg:

class CustomException extends \Exception
{

    private $_options;

    public function __construct($message, 
                                $code = 0, 
                                Exception $previous = null, 
                                $options = array('params')) 
    {
        parent::__construct($message, $code, $previous);

        $this->_options = $options; 
    }

    public function GetOptions() { return $this->_options; }
}

Then, in your calling code...

try 
{
   // some code that throws new CustomException($msg, $code, $previousException, $optionsArray)
}
catch (CustomException $ex)
{
   $options = $ex->GetOptions();
   // do something with $options[]...
}

Have a look at the php docs for extending the exception class:

http://php.net/manual/en/language.exceptions.extending.php

Cerebrovascular answered 22/7, 2011 at 23:28 Comment(0)
A
16

I think I'm a bit too late with an answer, but I wanted to share my solution as well. There are probably more people looking for this :)

class JsonEncodedException extends \Exception
{
    /**
     * Json encodes the message and calls the parent constructor.
     *
     * @param null           $message
     * @param int            $code
     * @param Exception|null $previous
     */
    public function __construct($message = null, $code = 0, Exception $previous = null)
    {
        parent::__construct(json_encode($message), $code, $previous);
    }

    /**
     * Returns the json decoded message.
     *
     * @param bool $assoc
     *
     * @return mixed
     */
    public function getDecodedMessage($assoc = false)
    {
        return json_decode($this->getMessage(), $assoc);
    }
}
Audriaaudrie answered 29/9, 2015 at 20:52 Comment(1)
adding true as a second parameter to json_decode will return an Array, if omittd an Object is returnedColdiron
M
10

If you don't want to extend Exception, you can encode your array into a string:

try {
  throw new Exception(serialize(['msg'=>"Booped up with %d.",'num'=>123]));
} catch (Exception $e) {
  $data = unserialize($e->getMessage());
  if (is_array($data))
    printf($data['msg'],$data['num']);
  else
    print($e->getMessage());
}

You can also use json_encode/json_decode if you prefer.

Modestomodesty answered 8/1, 2018 at 18:11 Comment(1)
It's better to use custom exception and unserialize the data from the custom _construct()Rectify
R
3

Yes, you can. You will need to extend the Exception class and create a __construct() method to do what you want.

Rice answered 22/7, 2011 at 23:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.