3

I have been trying to implement the following in a Rails app but it seems not to do anything at all:

rescue Twilio::REST::RequestError => e
    puts e.message

I notice it is only in the older docs for the twilio ruby gem, not in the newest ones. Is it no longer supported? Or do I need to change this code somehow?

I have tried to use the above when I get an invalid number or other error message from the Twilio API, but it doesn't work and just crashes the controller.

Here's an example of what I did:

rescue Twilio::REST::RequestError => e
    flash[:error] = e.message
1
  • 1
    Try rescue => e, then print out e.class to your console. See what exactly is being raised.
    – fbelanger
    Sep 4, 2016 at 22:35

2 Answers 2

3

Well, it was my bad. I hadn't properly implemented the block. I did the following and it works now:

def create
    begin
      to_number = message_params
      boot_twilio
      sms = @client.messages.create(
        from: ENV['TWILIO_NUMBER'],
        to: to_number,
        body: "..."
      )
    rescue Twilio::REST::RequestError => e
      flash[:error] = "..."
    else
      flash[:notice] = "..."
    end
    redirect_to path
  end
1

Twilio developer evangelist here.

If you are using the v5 release candidates then you will need to update the error class you are trying to catch.

The error raised in an HTTP request will be a Twilio::REST::RestException which inherits from the more generic Twilio::REST::TwilioException. See the error classes here: https://github.com/twilio/twilio-ruby/blob/next-gen/lib/twilio-ruby/framework/exception.rb

Note: I would not report the error message directly to the user. Those messages are intended for developers to better understand the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.