rescue Twilio::REST::RequestError not working - ruby-on-rails

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

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

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.

Related

Checking attachments synch failure with cURL on_failure callback

I am sending attachments from Redmine to JIRA. This is the code I'm using for it:
if attachments.present?
begin
curl = SynchCurl.get_jira_curl_instance "jira_url"
curl.multipart_form_post = true
curl.headers["X-Atlassian-Token"] = "no-check"
attachments.each do |sa|
curl.http_post(Curl::PostField.file('file', sa.disk_filename, remote_file_name = sa.filename))
end
rescue Exception => e
CommonSynch.manage_jira_errors e
end
end
Now I want to check if the attachments are being saved on JIRA via Easy Callbacks to show the user an error message. I tried with:
curl.on_failure {|easy| puts "Error message"}
And some modifications under the post request, but the callback is always getting a nil value (I modified my code to provoke a 500 response code).
How can I do this?
Sorry if this is a dumb question, im pretty new in RoR. Thanks in advance.

Yelp API exception Handling Ruby on Rails

I'm working on Yelp API through gem 'yelp' . Everything works fine but when we enter a location which is not provided by yelp it throws exception .
Yelp::Error::UnavailableForLocation
I have tried begin/end raise and rescue but not working . Can anyone tell , what's i'm doing wrong . here is what i tried
begin
client = Yelp::client
raise yelp_places_burst = client.search('lahore , pakistan')
end
rescue Exception => e
puts e.message
In addition , I want to send the error to js file (in response of ajax)
You are a little bit confused on how an exception is rescued. The way to rescue an exception in Ruby is
begin
# execution
rescue ErrorClass
# do something
end
Therefore your code should be
begin
client = Yelp::client
yelp_places_burst = client.search('lahore , pakistan')
rescue Yelp::Error::UnavailableForLocation => e
puts e.message
end
Also note I replaced Exception with the specific exception class. In fact, it's not recommended to rescue Exception as it will hide several other very exceptional events.
if you look at https://github.com/Yelp/yelp-ruby/blob/develop/lib/yelp/error.rb you can see that Yelp::Error::UnavailableForLocation is extended from Base which extends StandardError. So you need to catch StandardError, not Exception.
You get some additional explanations here: https://robots.thoughtbot.com/rescue-standarderror-not-exception, which suggests you can use rescue => e which will catch StandardError by default.

How to troubleshoot quickbooks-ruby

I have a Rails app set up with the quickbooks-ruby gem.
Oauth seems to be working—there are no errors, I follow the Quickbooks login in a pop-up, and I get a confirmation that the account is connected. No errors.
However, in my audit log on Quickbooks Online, there is not indication that I have logged in.
And when I follow the steps to try to get a list of customers, I get this error:
undefined method 'get' for "qyprd...":String
Which may or may not be a different problem.
This is the code:
def index
#customers = Customer.all
service = Quickbooks::Service::Customer.new
service.company_id = session[:realm_id]
service.access_token = session[:token]
customers = service.query()
end
I don't understand why it isn't working, or how to troubleshoot the issue.
From the above code I see you are not passing the query in last but one line. Query should look something like this i.e customers.query("Select Id, GivenName From Customer")
To understand why it isn't working and to troubleshoot the issue you can use begin and rescue.
begin
oauth_client = OAuth::AccessToken.new($qb_oauth_consumer, token, secret)
service = Quickbooks::Service::Customer.new(:access_token => oauth_client, :company_id => realm_id)
customers = customers.query("Select Id, GivenName From Customer")
rescue Exception => e
# e.message will show response of quickbooks for you request
puts e.message
# e.message.inspect will show logs
puts e.backtrace.inspect
end
You can also try your queries on API explorer and see if get the result set you want.

Dealing with Custom Exceptions Codes from Failed API Call

I'm connecting our Rails (3.2) application to an external web service (campaign monitor) which requires a few calls to their system to set a client up.
I've put each action into separate rescue blocks and wrapped in a transaction but things aren't looking so great. I need it to escape after each error and display the correct message. Currently it just escapes.
I have a list of possible errors per action - how is it possible to read these and format as a flash message?
For example, the following error:
CreateSend::BadRequest: The CreateSend API responded with the following error - 172: You can create a maximum of five (5) clients per thirty (30) minutes
I currently have this in my controller:
def create_send_setup
...
begin
client = CreateSend::Client.create(#user.company_name, #user.username, #user.email, "(GMT) Dublin, Edinburgh, Lisbon, London", #user.country)
rescue
flash[:notice] = "Uh oh, there's been a problem. Please try again. Client"
end
begin
#client = CreateSend::Client.new(#user.createsend_client_api)
#client.set_access(#user.username, #password, #user.createsend_access_level)
#client.set_monthly_billing(#user.createsend_currency, true, #user.createsend_markup)
rescue
flash[:notice] = "Uh oh, there's been a problem. Please try again. Access"
end
flash[:notice] = "Great, now you just need to choose a plan"
redirect_to edit_user_registration_path
end
In a previous integration, I've used something like
case bla.code.to_s
when /2../
when '403'
raise "Could not update subscriber: new-customer-id is already in use."
...
end
What's the best way to extract the error code from the response and display as a flash message?
All you can do is work with the exception given-if there's no data payload you can try to parse the message strings, use it as-is, map all or part of it to your own messages, etc.
For example, if the example message you show is normalized, a regex could be used to grab the numeric and message portions:
[1] pry(main)> s = "CreateSend::BadRequest: The CreateSend API responded with the following error - 172: You can create a maximum of five (5) clients per thirty (30) minutes"
=> "CreateSend::BadRequest: The CreateSend API responded with the following error - 172: You can create a maximum of five (5) clients per thirty (30) minutes"
[2] pry(main)> md = s.match /.*?- (\d+): (.*)/
=> #<MatchData
"CreateSend::BadRequest: The CreateSend API responded with the following error - 172: You can create a maximum of five (5) clients per thirty (30) minutes"
1:"172"
2:"You can create a maximum of five (5) clients per thirty (30) minutes">
[3] pry(main)> md[1]
=> "172"
[4] pry(main)> md[2]
=> "You can create a maximum of five (5) clients per thirty (30) minutes"
As Dave said, if the exception is all you've got, you can only capture the exception and do something with that exception as a string.
For example:
begin
...
rescue Exception => ex
# here "ex.message" contains your string, you can do anything you want with it
# or parse as is:
flash[:notice] = ex.message
end
redirect_to edit_user_registration_path
UPDATE
If you combine my proposed solution with those put forward by Dave, you'd get something like this, with which you can use your own error strings:
begin
...
rescue Exception => ex
code = ex.message.match(/.*?- (\d+): (.*)/)[1]
case code
when '172'
flash[:notice] = 'Please wait 30 minutes to create more clients'
end
end
redirect_to edit_user_registration_path
The best way of handling errors in this specific situation is by specifically handing the errors which the library defines itself. createsend-ruby defines CreateSendError, BadRequest, and Unauthorized. You do not need to parse any strings.
Here is an example take from the README, of handling errors:
require 'createsend'
CreateSend.api_key 'your_api_key'
begin
cl = CreateSend::Client.new "4a397ccaaa55eb4e6aa1221e1e2d7122"
id = CreateSend::Campaign.create cl.client_id, "", "", "", "", "", "", "", [], []
puts "New campaign ID: #{id}"
rescue CreateSend::BadRequest => br
puts "Bad request error: #{br}"
puts "Error Code: #{br.data.Code}"
puts "Error Message: #{br.data.Message}"
rescue Exception => e
puts "Error: #{e}"
end
The data field always contains a Code and Message, which correspond to the status codes API documentation.

Ruby on Rails - Checking against HTTP errors in controller

Just today I've found my fbgraph implementation has started returning a 400 Bad Request error which is causing an internal server error.
The controller looks like:
def fb
fbclient = FBGraph::Client.new(:client_id => 'ID', :secret_id => 'SECRET')
#fbname = fbclient.selection.user('129220333799040').feed.info!['data'][0].from.name
#fbmessage = fbclient.selection.user('129220333799040').feed.info!['data'][0].message
end
How can I check before calling #fbname in my view that I've received a 200 status?
Thanks.
Update: following Devin M's suggestion, I've switched the above action to
def fb
fbclient = FBGraph::Client.new(:client_id => 'ID', :secret_id => 'SECRET')
begin
#fbname = fbclient.selection.user('129220333799040').feed.info!['data'][0].from.name
#fbmessage = fbclient.selection.user('129220333799040').feed.info!['data'][0].message
rescue
#fbname = "Facebook Account"
#fbmessage = "Facebook's API is a nightmare"
end
end
I think that you should write some tests for this, Its hard to work with Facebooks nightmare of an API.
Although if you wanted to catch this error try using that way you can catch the specific error and take some action on it in the rescue portion.
begin
rescue
end
If you want me to take a look at the docs and see what you should catch let me know.

Resources