php 异常额外参数
2022-08-30 18:23:28
是否可以在引发异常时添加额外的参数?
当我抛出异常时,我会发送错误消息,但我也想在额外的参数中发送字段的名称。像这样:
throw new Exception('this is an error message', 'the field');
因此,当我显示消息时,我可以执行如下操作:
show_error($e->getFieldname, $e->getMessage());
是否可以在引发异常时添加额外的参数?
当我抛出异常时,我会发送错误消息,但我也想在额外的参数中发送字段的名称。像这样:
throw new Exception('this is an error message', 'the field');
因此,当我显示消息时,我可以执行如下操作:
show_error($e->getFieldname, $e->getMessage());
不,您必须使用自己的实现子类 Exception 并添加该方法。
class FieldException extends Exception
{
protected $_field;
public function __construct($message="", $code=0 , Exception $previous=NULL, $field = NULL)
{
$this->_field = $field;
parent::__construct($message, $code, $previous);
}
public function getField()
{
return $this->_field;
}
}
但实际上,我不是向异常添加方法或属性的朋友。异常仅表示:应用程序中发生的异常情况。“field”属性实际上不是 Exception 的一部分,而是异常消息的一部分,所以我可能会使用正确的消息,如下所示:
字段 foo 的值错误。例外字符串,获取整数
无需添加额外的参数。
你可以像这样抛出一个异常:
throw new Exception("My Exception Text", 1234);
并访问这两个值:
catch (Throwable $t)
{
echo var_dump($t);
echo "Exception: " . $t->getMessage();
echo "Code: " . $t->getCode();
}