Not able to catch exception sending SMS with Twilio in plugin Not sure if this is the best place to post, but since it's a Craft 3 plugin I'll give it a shot.

foreach ($numbers as $number){
    $number = $twilio-&gt;lookups-&gt;v1-&gt;phoneNumbers($user-&gt;mobil)-&gt;fetch(['countryCode' =&gt; 'NO'])-&gt;phoneNumber;

    try {
        // Send SMS
        $twilio-&gt;messages-&gt;create(
            $number,
            [
                'from' =&gt; $settings-&gt;twilioNumber,
                'body' =&gt; $request-&gt;post('body')
            ]
        );
    } catch (\Exception $e) {
        continue; // Continue (loop) to next number as this one failed/is invalid.
    }
}


In short, whenever a $number is invalid, execution stops giving Twilio\Exceptions\RestException [HTTP 404] Unable to fetch record: The requested resource /PhoneNumbers/"the-invalid-number" was not found.

It seems that the catch is never reached.

Note that I have tried replacing \Exception with the following to no avail.

use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\DeserializeException;
use Twilio\Exceptions\EnvironmentException;
use Twilio\Exceptions\HttpException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwimlException;


Regardless, I thought \Exception would catch any exception?

Edit: Here's the solution.

try {
    // Validate the number
    $number = $twilio-&gt;lookups-&gt;v1-&gt;phoneNumbers($user-&gt;mobil)-&gt;fetch(['countryCode' =&gt; 'NO'])-&gt;phoneNumber;

    // Send SMS
    $twilio-&gt;messages-&gt;create(
        $number,
        [
            'from' =&gt; $settings-&gt;twilioNumber,
            'body' =&gt; $request-&gt;post('body')
        ]
    );
} catch (\Exception $e) {
    // Number is invalid; continue to next number
    continue;
}
The exception is thrown before you enter your catch block during this line

 $number = $twilio-&gt;lookups-&gt;v1-&gt;phoneNumbers($user-&gt;mobil)-&gt;fetch(['countryCode' =&gt; 'NO'])-&gt;phoneNumber; 


That's why it can't be cached. Move it into the same block and handle every single possible exception that can be thrown accordingly or via generic \Exception class