我想在 php 中抛出一个数组作为异常,而不是字符串。如果您定义自己的类来扩展 Exception 类,是否可以做到这一点?
例如throw new CustomException('string', $options = array('params'));
当然。这仅取决于您的错误处理代码要注意的问题,并适当地使用数组属性。您可以定义自定义异常类的构造函数来获取所需的任何参数,然后确保从构造函数定义中调用基类的构造函数,例如:
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 http://php.net/manual/en/language.exceptions.extending.php
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)