donglan9651 2016-11-23 16:05
浏览 58
已采纳

如何从另一个类中捕获异常?

I have a custom class:

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
    }
}

So, when I call $this->sms->sendSms I get an error from class sms.

I'm catching the custom exception like as:

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

But when I get the error inside the library (class SmsSender) in method: send() I can not catch it and I get the error.

How can I fix it?

  • 写回答

1条回答 默认 最新

  • doumisha5081 2016-11-23 16:57
    关注

    It's possibly a namespace thing.

    If SmsException is defined within a namespace, for example:

    <?php namespace App\Exceptions;
    
    class SmsException extends \Exception {
        //
    }
    

    and the code that is trying to catch the exception is defined within another namespace, or none at all, for example:

    <?php App\Libs;
    
    class MyLib {
    
        public function foo() {
            try {
    
                $activationService = new ActivationService();
                $activationService->send($request->phone);
    
            } catch (SmsException $e) {
    
                echo 'Caught exception: ', $e->getMessage(), "
    ";
            }
        }
    }
    

    then it will actaully be trying to catch App\Libs\SmsException, which isn't defined so the catch fails.

    If this is the case try replacing catch (SmsException $e) with catch (\App\Exceptions\SmsException $e) (obviously use the correct namespaces), or put a use statement at the top of the file.

    <?php App\Libs;
    
    use App\Exceptions\SmsException;
    
    class MyLib {
    
        // Code here...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)