首页 > 解决方案 > 如何从调用的函数中捕获错误?

问题描述

好的,我有问题,catch或者errorexception我打电话给undefined function

我有一个调用函数的方法,有两个参数(bool, function)

private function invoking($hdr = true, $fnc) {
   if(is_callable($fnc)) {
      if($hdr) {
         $this->load_header();
      }

      try {
        $fnc->__invoke();
      } catch(Exception $er) {
        echo "Something went wrong. ".$er;
      }
   } else {
       echo "function not callable";
   }
}

但是,我有一个问题来捕捉里面的错误$fnc

$this->invoking(true, function() {
   undefinedfunction();
   // for example i called this, which the function doesnt exist
});

但是似乎 catch 对 i 内部的内容不起作用__invoke(),我应该怎么做才能捕获invoked函数内部的错误?

感谢您的任何建议

标签: phptry-catchinvoke

解决方案


但似乎捕获不适用于 i __invoke() 内部的内容

它不起作用,因为它抛出了一个Fatal error无法使用Exception类处理的问题。在 PHP 7 之前,几乎不可能捕获这些错误。

在 PHP 7 中:

现在大多数错误都是通过抛出错误异常来报告的

阅读更多关于PHP 7 中的错误

因此,如果您的 php 版本 >= PHP 7,您可以这样做

  try {
    $fnc->__invoke();
  } catch(Error $er) { // Error is the base class for all internal PHP errors
    echo $er->getMessage();
  }

推荐阅读