Search code examples
phplaravelexceptionlaravel-5.3

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'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(), "\n";
}

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?


Solution

  • 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(), "\n";
            }
        }
    }
    

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