Anand agrawal
Anand agrawal

Reputation: 523

An uncaught Exception was encountered Type: Twilio\Exceptions\RestException

I am using SDK of Twilio messaging service and they provided functionality to verify phone/mobile numbers, it is working good if number is valid, but giving

An uncaught Exception was encountered Type: Twilio\Exceptions\RestException

If number is not valid, after getting this error my function stop working. I am using codeigniter to call its SDK functions,

Please help me how to handle this error.

public function verify($contact_no){
    $sid = "AccountSID";
    $token = "Token";
    $client = new Client($sid, $token);
    $encoded = rawurlencode("$contact_no");
    $number = $client->lookups
                     ->phoneNumbers($encoded)
                     ->fetch(
                       array("countryCode" => "US")
                    );
    if ($number->phoneNumber) {
        echo "True";
        $status = "valid";
     } else {
        echo "False";
        $status = 'invalid';
     }
     $data = array(
          "verify" => "$status"
     );
     $this->model->update_contact_verification($contact_no, $data);
}

Upvotes: 0

Views: 1908

Answers (1)

philnash
philnash

Reputation: 73027

Twilio developer evangelist here.

When the number is not recognised as a number, the Lookup API returns a 404. The PHP helper library throws a RestException for that, so you need to catch the error. You should update your code to something like this:

public function verify($contact_no){
    $sid = "AccountSID";
    $token = "Token";
    $client = new Client($sid, $token);
    $encoded = rawurlencode("$contact_no");
    try {
        $number = $client->lookups
                      ->phoneNumbers($encoded)
                      ->fetch(
                        array("countryCode" => "US")
                      );
        echo $number->phoneNumber;
        $status = 'valid';
    } catch (Twilio\Exceptions\RestException $e) {
        echo "False";
        $status = 'invalid';
    }
    $data = array(
        "verify" => "$status"
    );
    $this->model->update_contact_verification($contact_no, $data);
}

Let me know if that helps at all.

Upvotes: 2

Related Questions