ruby - How to deal with Twilio API SMS errors and invalid phone numbers in Rails -


how can handle errors in twilio api in regards creating sms message?

every time invalid phone number gets entered, message , 500 error:

unable create record: 'to' number not valid phone number.

how can have redirect home page , flash 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 current watch list:\n#{movies}"     )   puts text_message.to end end 

i don't need fancy, redirect main page , quick error message saying phone number invalid, not 500 error page. i'm new twilio api, , i've been troubleshooting issue hours.

twilio developer evangelist here.

when make request twilio api using ruby gem , goes wrong, library throw error of type twilio::rest::resterror.

in order avoid 500 error user should rescue error , else controller. i'm not sure controller looks like, i'll take guess @ should do.

first, i'd update messager class store error message if one. also, send_message function should return boolean describe whether message 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 current watch list:\n#{movies}"       )       return true     rescue twilio::rest::resterror => error       @error = error       return false     end   end end 

then, in controller can call send_message , different things if message 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!       # going successfull result     else       # boo, happened.       rails.logger.warn("#{messager.error.code}: #{messager.error.message}")       # redirect or render action error here.     end   end end 

let me know if helps @ all.


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -