代码之家  ›  专栏  ›  技术社区  ›  Irvan Hilmi

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

  •  -1
  • Irvan Hilmi  · 技术社区  · 7 年前

    好吧,我有个问题要问 catch 一 error 或 exception 当我打电话给 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
    });
    

    但似乎这个陷阱对我的内心不起作用 __invoke() invoked 功能?

    谢谢你的建议

    2 回复  |  直到 7 年前
        1
  •  1
  •   Rain cheladon    7 年前

    但是看起来这个陷阱对我调用的东西不起作用

    它不起作用,因为它抛出了一个 Fatal error 不能使用 Exception

    在PHP 7中:

    阅读更多关于 Errors in PHP 7

    因此,如果您的php版本为>=PHP7您可以简单地这样做

      try {
        $fnc->__invoke();
      } catch(Error $er) { // Error is the base class for all internal PHP errors
        echo $er->getMessage();
      }
    
        2
  •  0
  •   Ibrahim E.Gad    7 年前

    在传递undefinedfunction之前,您正在执行该函数

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

    那么u_invoke对字符串不起作用,所以需要使用

    call_user_func($fnc);
    

    相反

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

    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"));