2017-10-16 65 views
4

我的例子:如何处理其他try catch块中的异常?

class CustomException extends \Exception { 

} 

class FirstClass { 
    function method() { 
     try { 
      $get = external(); 
      if (!isset($get['ok'])) { 
       throw new CustomException; 
      } 

      return $get; 
     } catch (Exception $ex) { 
      echo 'ERROR1'; die(); 
     } 
    } 
} 

class SecondClass { 
    function get() { 
     try { 
      $firstClass = new FirstClass(); 
      $get = $firstClass->method(); 
     } catch (CustomException $e) { 
      echo 'ERROR2'; die(); 
     } 
    } 
} 

$secondClass = new SecondClass(); 
$secondClass->get(); 

这回我 “ERROR1”,但我想从二等收到 “ERROR2”。

在FirstClass块中,try catch应该处理来自external()方法的错误。

我该怎么做?

回答

0

而不是打印一个错误消息和死整个php进程,你应该抛出另一个异常,并注册一个全局异常处理程序,它为未处理的异常处理异常。

class CustomException extends \Exception { 

} 

class FirstClass { 
    function method() { 
     try { 
      $get = external(); 
      if (!isset($get['ok'])) { 
       throw new CustomException; 
      } 

      return $get; 
     } catch (Exception $ex) { 
      // maybe do some cleanups.. 
      throw $ex; 
     } 
    } 
} 

class SecondClass { 
    function get() { 
     try { 
      $firstClass = new FirstClass(); 
      $get = $firstClass->method(); 
     } catch (CustomException $e) { 
      // some other cleanups 
      throw $e; 
     } 
    } 
} 

$secondClass = new SecondClass(); 
$secondClass->get(); 

你可以注册set_exception_handler

set_exception_handler(function ($exception) { 
    echo "Uncaught exception: " , $exception->getMessage(), "\n"; 
}); 
一个全球性的异常处理程序