如何捕获另一个 class 的异常?

How to catch an exception from another class?

我有一个习惯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
    }
}

所以,当我调用 $this->sms->sendSms 时,我收到来自 class sms 的错误。

我正在捕获自定义异常,如下所示:

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

但是当我在库 (class SmsSender) 中的方法中遇到错误时:send() 我无法捕捉到它并收到错误。

我该如何解决?

这可能是命名空间的问题。

如果SmsException定义在命名空间内,例如:

<?php namespace App\Exceptions;

class SmsException extends \Exception {
    //
}

并且试图捕获异常的代码是在另一个名称空间中定义的,或者完全是 none,例如:

<?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 (SmsException $e) 替换为 catch (\App\Exceptions\SmsException $e)(显然使用正确的命名空间),或者在文件顶部放置一个 use 语句。

<?php App\Libs;

use App\Exceptions\SmsException;

class MyLib {

    // Code here...