How to catch an exception from another class?

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 where the error appeared
    }
}

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

I will catch a custom exception like:

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

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

How can i fix this?

+4
source share
1 answer

Perhaps this is a namespace.

If SmsExceptiondefined in a namespace, for example:

<?php namespace App\Exceptions;

class SmsException extends \Exception {
    //
}

and the code that tries to catch the exception is defined in another namespace or is missing 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(), "\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...
+1

Source: https://habr.com/ru/post/1661737/


All Articles