0

I'm trying to pass an array to the Exception class and I get an error stating:

PHP Fatal error:  Wrong parameters for Exception([string $exception [, long $code [, Exception $previous = NULL]]])

Obviously, this means that the standard Exception class does not handle these variable types, so I would like to extend the Exception class to a custom exception handler that can use strings, arrays, and objects as the message type.

class cException extends Exception {

   public function __construct($message, $code = 0, Exception $previous = null) {
      // make sure everything is assigned properly
      parent::__construct($message, $code, $previous);
   }

}

What needs to happen in my custom exception to reformat the $message argument to allow for these variable types?

4

2 回答 2

1

这取决于您希望您的信息如何发挥作用。最简单的方法是向构造函数添加一些代码,根据类型将消息转换为字符串。仅使用 print_r 是最简单的。在传递给父 __construct 之前尝试添加它。

$message = print_r($message, 1);
于 2013-06-20T16:04:14.097 回答
1

将自定义 getMessage() 函数添加到您的自定义异常中,因为无法覆盖最终的 getMessage。

class CustomException extends Exception{
    private $arrayMessage = null;
    public function __construct($message = null, $code = 0, Exception $previous = null){
        if(is_array($message)){
            $this->arrayMessage = $message;
            $message = null;
        }
        $this->exception = new Exception($message,$code,$previous);
    }
    public function getCustomMessage(){
        return $this->arrayMessage ? $this->arrayMessage : $this->getMessage();
    }
}

捕获 CustomException 时,调用 getCustomMessage() 将返回您在 $message 参数中传递的任何内容

try{
    ..
}catch(CustomException $e){
    $message $e->getCustomMessage();
}
于 2014-02-05T22:40:33.140 回答