Emil
Emil

Reputation: 63

rescue Twilio::REST::RequestError not working

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

Upvotes: 3

Views: 913

Answers (2)

Emil
Emil

Reputation: 63

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

Upvotes: 3

philnash
philnash

Reputation: 73100

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.

Upvotes: 1

Related Questions