如何从调用的函数中捕获错误?

时间:2018-11-09 04:06:58

标签: php try-catch invoke

好的,我在打电话给catch error时遇到exceptionundefined的问题

我有一个方法来调用带有两个参数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 }); 内部的内容不起作用,我应该怎么做才能捕获__invoke()函数内部的错误?

谢谢您的建议

2 个答案:

答案 0 :(得分:1)

  

但是似乎捕获对我__invoke()里面的内容不起作用

它不起作用,因为它抛出了Fatal error类无法处理的Exception。在PHP 7之前,几乎不可能捕获到此类错误。

在PHP 7中:

  

现在大多数错误是通过引发Error异常报告的

详细了解Errors in PHP 7

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

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

答案 1 :(得分:0)

您正在执行未定义的函数,然后再传递它 您需要这样做:

$this->invoking(true,'undefinedfunction');

然后__invoke在字符串上不起作用,因此您需要使用

call_user_func($fnc);

相反。

要调用具有参数的函数,请将参数作为数组传递给函数,然后传递给 call_user_func_array

private function invoking($hdr = true, $fnc, $args=Array())
...
call_user_func_array($fnc, $args);
...
$this->invoking(true,'print_r', Array("Hi there It Works"));

因此您的最终代码将是:

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

      try {
        call_user_func_array($fnc, $args);
      } catch(Exception $er) {
        echo "Something went wrong. ".$er;
      }
   } else {
       echo "function not callable";
   }
}

测试:

$this->invoking(true,'undefinedfunction');
$this->invoking(true,'print_r', Array("Hi there It Works"));