php 你能在php中抛出一个数组而不是一个字符串作为异常吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6797142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:16:56  来源:igfitidea点击:

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

phpcustom-exceptions

提问by john mossel

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?

我想在 php 中抛出一个数组作为异常,而不是一个字符串。如果您定义自己的扩展 Exception 类的类,是否可以执行此操作?

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

例如 throw new CustomException('string', $options = array('params'));

回答by echo

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:

查看用于扩展异常类的 php 文档:

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

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

回答by Rolf

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

回答by Sinus Mackowaty

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_decodeif you prefer.

如果您愿意,也可以使用json_encode/ json_decode

回答by Mike

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

是的你可以。您将需要扩展Exception 类并创建一个 __construct() 方法来执行您想要的操作。