title: Catch Error from external API in Rails
body: <p>I am building a simple web app that sends SMS messages to cell phones using Twilio. I want to ensure that the user has entered a full 10 digit phone number before it will allow a message to attempt to be sent.</p>
  
  <p>When I test it with a less-than or greater-than 10 digit number, in <code>heroku logs</code>, I see <code>Twilio::REST::RequestError (The 'To' number 1234567890 is not a valid phone number.)</code>.</p>
  
  <p>I have tried to use a <code>begin</code>/<code>rescue</code> wrapper and am telling it to <code>render text: "Try again with a valid number."</code> and tried a variety of <code>if</code> statements to try to avoid the error.</p>
  
  <p>I am pretty new to Ruby and Rails and Twilio, but I promise i have been through every guide I have found. Any help is greatly appreciated. Full code of my <code>UserController</code> below:</p>
  
  <pre><code>    require 'twilio-ruby'
      class UsersController &lt; ApplicationController
  
      def new
        @user = User.new
      end
  
      def create
        @user = User.new(params[:user])
  
        account_sid = '...'
        auth_token = '...'
  
        if @user.save
           render text: "Wasn't that fun? Hit the back button in your browser to give it another go!"
      begin
         client = Twilio::REST::Client.new account_sid, auth_token
             client.account.sms.messages.create(
             from: '+16035093259',
             to: @user.phone,
             body: @user.message
             )
          rescue Twilio::REST::RequestError
             render text: "Try again with a valid number."        
          end
       else
         render :new
       end
    end
  
  end
  </code></pre>