2017-10-16 59 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"; 
}); 
一個全球性的異常處理程序