duanliusong6395 2013-06-20 14:38
浏览 107
已采纳

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

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条回答 默认 最新

  • doz15449 2014-02-05 22:40
    关注

    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();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应