2016-11-23 55 views
4

我有一個自定義類:如何從另一個類捕獲異常?

class ActivationService extends SmsException { 

    public function __construct() 
    { 
      $this->sms = new SmsSender(); 
    } 

    public function method(){ 
     throw new SmsException(); // My custom exception 
    } 


    public function send(){ 
     $this->sms->sendSms($this->phone); // Here's where the error appeared 
    } 
} 

所以,當我打電話$this->sms->sendSms我從sms類得到一個錯誤。

我趕上了自定義異常等爲:

try {  
    $activationService = new ActivationService(); 
    $activationService->send($request->phone);  
} 
catch (SmsException $e) {  
    echo 'Caught exception: ', $e->getMessage(), "\n"; 
} 

但是當我拿到方法庫(class SmsSender)裏面的錯誤:send()我不能抓住它,我得到的錯誤。

我該如何解決?

+0

它可能不會拋出SmsException。爲'\ Exception'添加另一個catch塊並查看是否捕獲了某些內容。 –

+0

是的,'\ Exception'可以工作,但爲什麼我的異常不起作用,如果有:'use Exception; 類SmsException擴展異常 { // TODO }' – Goga

+0

您是否需要'\ SmsException'?我知道命名空間可能會擾亂這一點。 – nerdlyist

回答

1

這可能是一個命名空間的事情。

如果SmsException是一個命名空間中定義,例如:

<?php namespace App\Exceptions; 

class SmsException extends \Exception { 
    // 
} 

並試圖捕捉到了異常的另一個命名空間中定義的代碼,或根本沒有,例如:

<?php App\Libs; 

class MyLib { 

    public function foo() { 
     try { 

      $activationService = new ActivationService(); 
      $activationService->send($request->phone); 

     } catch (SmsException $e) { 

      echo 'Caught exception: ', $e->getMessage(), "\n"; 
     } 
    } 
} 

那麼它將實際上試圖捕獲App\Libs\SmsException,這是沒有定義,所以catch失敗。

如果是這種情況,請嘗試用catch (\App\Exceptions\SmsException $e)替換catch (SmsException $e)(顯然使用正確的名稱空間),或將use語句放在文件的頂部。

<?php App\Libs; 

use App\Exceptions\SmsException; 

class MyLib { 

    // Code here...