0

I am trying to check for toll-free numbers, and it is working as expected. However, my problem is that some countries don't have the TollFree numbers.

Using the same code on these countries throws a 404 error and stops the code there.

The only way I could think of is making a massive if statement and adding each country manually which offers toll-free option, but I don't like this solution at all as it will be hardcoded. Is there a way to overcome this issue, so it works for the countries that has the .json and ignore the ones that doesn't (instead of crashing the code)?

$twilio = new Client(env('TWILIO_ID'), env('TWILIO_TOKEN'));
$iso = 'CY';
$params = ["excludeLocalAddressRequired" => "true"];

$tollFreeNumbers = $twilio->availablePhoneNumbers($iso)->tollFree->read($params);

This is the response:

"[HTTP 404] Unable to fetch page: The requested resource /2010-04-01/Accounts/ACxxxxx/AvailablePhoneNumbers/CY/TollFree.json was not found"

Using this code will crash with CY but will work with UK, US, CA and many more. Should I add an if statement with hardcoded countries? (I really dislike this solution, but this is what I can think of). What I mean is:

if ($iso == 'GB' || $iso == 'US' || $iso == 'CA') {     // and many more
    $tollFreeNumbers = $twilio->availablePhoneNumbers($iso)->tollFree->read($params);
}
senty
  • 10,294
  • 23
  • 99
  • 215

2 Answers2

1

Why not just wrap it in a try catch?

try {
    $tollFreeNumbers = $twilio->availablePhoneNumbers($iso)->tollFree->read($params);
} catch(\Exception $e) {
    $tollFreeNumbers = [];
}
dave
  • 50,635
  • 4
  • 62
  • 77
1

Twilio developer evangelist here.

Rather than guarding up front with a conditional (which could become out of date as we add toll free numbers in other countries in the future), why not catch the error and return a message to the user to say that toll free numbers are not available in the country they are searching in.

Something like:

try {
  $tollFreeNumbers = $twilio->availablePhoneNumbers($iso)->tollFree->read($params);
} catch (Exception $e) {
  $tollFreeNumbers = [];
  $message = "Toll free numbers are not available in this country.";
}

Let me know if that helps at all.

philnash
  • 53,704
  • 10
  • 46
  • 69