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

发布于 2024-11-25 18:18:16 字数 154 浏览 2 评论 0原文

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一枫情书 2024-12-02 18:18:16

当然。这仅取决于您的错误处理代码要注意的问题,并适当地使用数组属性。您可以定义自定义异常类的构造函数来获取所需的任何参数,然后确保从构造函数定义中调用基类的构造函数,例如:

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

然后,在您的调用代码中...

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

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

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

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

海拔太高太耀眼 2024-12-02 18:18:16

我想我的答案有点太晚了,但我也想分享我的解决方案。可能还有更多人在寻找这个:)

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

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);
    }
}
最近可好 2024-12-02 18:18:16

如果您不想扩展 Exception,可以将数组编码为字符串:

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

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

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.

木森分化 2024-12-02 18:18:16

是的,你可以。您需要扩展 Exception 类 并创建一个 __construct() 方法做你想做的事。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文