简体   繁体   中英

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:

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?

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. Try adding this before passing to the parent __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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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