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

后端 未结 4 1233
说谎
说谎 2021-02-07 00:22

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 exampl

4条回答
  •  灰色年华
    2021-02-07 00:46

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

提交回复
热议问题