简体   繁体   English

PHP使异常接受数组和对象类型的消息

[英]PHP Make Exception Accept Messages of Array and Object Type

I'm trying to pass an array to the Exception class and I get an error stating: 我正在尝试将数组传递给Exception类,我得到一个错误说明:

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. 显然,这意味着标准的Exception类不处理这些变量类型,因此我想将Exception类扩展为可以使用字符串,数组和对象作为消息类型的自定义异常处理程序。

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? 在我的自定义异常中需要重新格式化$message参数以允许这些变量类型?

It depends on how you want your message to work. 这取决于您希望消息的工作方式。 The simplest way would be to add some code to the constructor that converts the message to a string depending on the type. 最简单的方法是向构造函数添加一些代码,根据类型将消息转换为字符串。 Just using print_r is the easiest. 只使用print_r是最简单的。 Try adding this before passing to the parent __construct. 尝试在传递给父__construct之前添加它。

$message = print_r($message, 1);

Add a custom getMessage() function to your custom exception, since it's not possible to override the final getMessage. 将自定义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();
    }
}

When catching the CustomException, call getCustomMessage() which will return whatever you've passed in the $message parameter 捕获CustomException时,调用getCustomMessage(),它将返回您在$ message参数中传递的内容

try{
    ..
}catch(CustomException $e){
    $message $e->getCustomMessage();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM