Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'));

like image 980
john mossel Avatar asked Jul 22 '11 23:07

john mossel


People also ask

What is an exception how you can handle multiple exceptions in PHP?

The primary method of handling exceptions in PHP is the try-catch. In a nutshell, the try-catch is a code block that can be used to deal with thrown exceptions without interrupting program execution. In other words, you can "try" to execute a block of code, and "catch" any PHP exceptions that are thrown.

What are exception types in PHP?

An exception is an object that describes an error or unexpected behaviour of a PHP script. Exceptions are thrown by many PHP functions and classes. User defined functions and classes can also throw exceptions. Exceptions are a good way to stop a function when it comes across data that it cannot use.

Does throwing an exception stop execution PHP?

When an exception is thrown, the code following it will not be executed, and PHP will try to find the matching "catch" block. If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message.


3 Answers

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

like image 188
echo Avatar answered Nov 13 '22 00:11

echo


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);
    }
}
like image 25
Rolf Avatar answered Nov 13 '22 02:11

Rolf


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.

like image 30
Sinus the Tentacular Avatar answered Nov 13 '22 02:11

Sinus the Tentacular