【问题标题】:PHP custom exception messagePHP自定义异常消息
【发布时间】:2011-06-30 21:15:15
【问题描述】:

如果方法不存在 Method()getMethod(),我正在尝试显示自定义错误消息:

public function __call($name, $args = array()){
  $getter = "get{$name}";

  try {
    echo call_user_func_array(array(&$this, $getter), $args);
  } catch (Exception $e) {

    trigger_error($e->getFile.' on line '.$e->getLine.': Method '.$name.' is not defined.', E_USER_ERROR)
  }
}

但它不起作用。我在浏览器中收到“连接被远程服务器关闭”消息:|

【问题讨论】:

标签: php exception error-handling


【解决方案1】:

您将使用method_exists 函数:

if(!method_exists($this, $name))
{
    // trigger_error(...);
}

如果您想要数据,例如调用无效方法的位置,您可以使用debug_backtrace

class X
{
    public function __call($name, $a)
    {
        $backtrace = debug_backtrace();
        $backtrace = $backtrace[1];
        // $backtrace['file']
        // $backtrace['line']
        // $backtrace['function']
        // $backtrace['class']
        // $backtrace['object']
    }
}

$o = new X();
$o->Hello();

【讨论】:

  • @Alex:是的,检查我的答案。只需访问我列出的那些数组元素。
  • 你只需要 throw new Exception('...');
猜你喜欢
  • 2012-01-17
  • 2013-07-05
  • 2015-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多