编程语言
首页 > 编程语言> > PHP自定义异常消息

PHP自定义异常消息

作者:互联网

如果某个方法不以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)
  }
}

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

解决方法:

您将使用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();

标签:error-handling,exception,php
来源: https://codeday.me/bug/20191208/2089836.html