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?

2 Answers 2

2

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();
}
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.