Reputation: 28
How can I handle errors in the Twilio API in regards to creating an SMS message?
Every time an invalid phone number gets entered, I get a message and a 500 error:
Unable to create record: The 'To' number is not a valid phone number.
How can I have it redirect back to the home page and simply flash an error notice?
class Messager
def initialize
@account_sid = ENV['ACCOUNT_SID']
@auth_token = ENV['AUTH_TOKEN']
@twilio_number = ENV['TWILIO_NUMBER']
@client = Twilio::REST::Client.new @account_sid, @auth_token
end
def send_message(phone_number, movies, username)
text_message = @client.api.account.messages.create(
from: @twilio_number,
to: phone_number,
body: "Hello movie lover, #{username}!\nHere is your current watch list:\n#{movies}"
)
puts text_message.to
end
end
I don't need anything fancy, just a redirect to the main page and a quick error message saying their phone number is invalid, not a 500 error page. I'm new to the Twilio API, and I've been troubleshooting this issue for hours.
Upvotes: 1
Views: 2471
Reputation: 73027
Twilio developer evangelist here.
When you make a request to the Twilio API using the Ruby gem and something goes wrong, the library will throw an error of type Twilio::REST::RestError
.
In order to avoid a 500 error for your user you should rescue from this error and do something else with your controller. I'm not sure what your controller looks like, so I'll take a guess at what you should do.
First, I'd update the Messager
class to store the error message if you get one. Also, the send_message
function should return a boolean to describe whether the message was successfully sent.
class Messager
attr_reader :error
def initialize
@account_sid = ENV['ACCOUNT_SID']
@auth_token = ENV['AUTH_TOKEN']
@twilio_number = ENV['TWILIO_NUMBER']
@client = Twilio::REST::Client.new @account_sid, @auth_token
end
def send_message(phone_number, movies, username)
begin
text_message = @client.api.account.messages.create(
from: @twilio_number,
to: phone_number,
body: "Hello movie lover, #{username}!\nHere is your current watch list:\n#{movies}"
)
return true
rescue Twilio::REST::RestError => error
@error = error
return false
end
end
end
Then, in your controller you can call send_message
and do different things if the message is successful or otherwise.
class MessagingController < ApplicationController
def create
messager = Messager.new
if messager.send_message(params[:phone_number], current_user.movies, current_user.username)
# Success! Message sent!
# Now do what you were going to do with the successfull result
else
# Boo, something happened.
Rails.logger.warn("#{messager.error.code}: #{messager.error.message}")
# Redirect or render an action with an error here.
end
end
end
Let me know if that helps at all.
Upvotes: 8