Ruby on Rails - Checking against HTTP errors in controller - ruby-on-rails

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.

Related

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
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.

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.

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.

ROR error with Salesforce: The requested resource does not exist

I am using the Ruby Gem "databascdotcom" to integrate Salesforce in a Rails app and all works fine.
But getting following error on first call to salesforce:
**The requested resource does not exist**
If I refresh (Ctrl + F5) the page again, it works fine without any error.
Here is my code:
def SalesForceFeed
#oppID = params[:oppid]
client = Databasedotcom::Client.new client.client_id #=> foo client.client_secret #=> bar
client.authenticate :username => "foo#bar.com", :password => "ThePasswordTheSecurityToken" #=> "the-oauth-token"
client.materialize("Opportunity")
begin
#client=SalesForce::Connection.new.client
#opp = Opportunity.find_by_Id(#oppID)
rescue Exception=>e
if(e.message == "The requested resource does not exist")
return redirect_to :action => 'SalesForceFeed', :oppid => #oppID
end
end
On the first call to "SalesForceFeed" it returned the error "The requested resource does not exist", so I added an excepton check and called "SalesForceFeed" again, but I know this is not the right way.
Please suggest me a better way to fix this. Thanks.
Finally i got the issue. There was a wrong object added in materialize. I removed that and it's fixed.

Problems with MailChimp API in Ruby Error Code: -90

I am using the following code in my MailChimp Controller to submit simple newsletter data. When It is sent I receive the following error as a "Method is not exported by this server -90" I have attached my controller code below. I am using this controller for a simple newsletter signup form. (Name, Email)
class MailchimpController < ApplicationController
require "net/http"
require "uri"
def subscribe
if request.post?
mailchimp = {}
mailchimp['apikey'] = 'f72328d1de9cc76092casdfsd425e467b6641-us2'
mailchimp['id'] = '8037342dd1874'
mailchimp['email_address'] = "email#gmail.com"
mailchimp['merge_vars[FNAME]'] = "FirstName"
mailchimp['output'] = 'json'
uri = URI.parse("http://us2.api.mailchimp.com/1.3/?method=listSubscribe")
response = Net::HTTP.post_form(uri, mailchimp)
mailchimp = ActiveSupport::JSON.decode(response.body)
if mailchimp['error']
render :text => mailchimp['error'] + "code:" + mailchimp['code'].to_s
elsif mailchimp == 'true'
render :text => 'ok'
else
render :text => 'error'
end
end
end
end
I highly recommend the Hominid gem: https://github.com/tatemae-consultancy/hominid
The problem is that Net::HTTP.post_form is not passing the "method" GET parameter. Not being a big ruby user, I'm not certain what the actual proper way to do that with Net::HTTP is, but this works:
require "net/http"
data="apikey=blahblahblah"
response = nil
Net::HTTP.start('us2.api.mailchimp.com', 80) {|http|
response = http.post('/1.3/?method=lists', data)
}
p response.body
That's the lists() method (for simplicity) and you'd have to build up (and urlencode your values!) your the full POST params rather than simply providing the hash.
Did you take a look at the many gems already available for ruby?
http://apidocs.mailchimp.com/downloads/#ruby
The bigger problem, and main reason I'm replying to this, is that your API Key is not obfuscated nearly well enough. Granted I'm used to working with them, but I was able to guess it very quickly. I would suggest immediately going and disabling that key in your account and then editing the post to actually have completely bogus data rather than anything close to the correct key. The list id on the other hand, doesn't matter at all.
You'll be able to use your hash if you convert it to json before passing it to Net::HTTP. The combined code would look something like:
mailchimp = {}
mailchimp['apikey'] = 'APIKEYAPIKEYAPIKEYAPIKEY'
mailchimp['id'] = '8037342dd1874'
mailchimp['email_address'] = "email#gmail.com"
mailchimp['merge_vars[FNAME]'] = "FirstName"
mailchimp['output'] = 'json'
response = nil
Net::HTTP.start('us2.api.mailchimp.com', 80) {|http|
response = http.post('/1.3/?method=listSubscribe', mailchimp.to_json)
}

Resources