我正在构建一个简单的 Web 应用程序,它使用 Twilio 将 SMS 消息发送到手机。我想确保用户在允许尝试发送消息之前输入了完整的 10 位电话号码。
当我用小于或大于 10 位的数字对其进行测试时,在 中heroku logs
,我看到了Twilio::REST::RequestError (The 'To' number 1234567890 is not a valid phone number.)
。
我尝试使用begin
/rescue
包装器并告诉它render text: "Try again with a valid number."
并尝试了各种if
语句来避免错误。
我对 Ruby、Rails 和 Twilio 还很陌生,但我保证我已经阅读了我找到的所有指南。任何帮助是极大的赞赏。我的完整代码UserController
如下:
require 'twilio-ruby'
class UsersController < 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