Search code examples
phparraysclassexceptionextend

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?


Solution

  • 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();
    }