semiflex
semiflex

Reputation: 1246

Escape/continue running program if error (Ruby)

I want to try and run my code, even if I encounter an error. I'll state where I believe I get the error below and what the error is:

require 'rubygems'
require 'simple_oauth'
require 'cloudsight'
require 'rubygems'
require 'net/http'
require 'uri'
require 'json'
require 'open-uri'
require 'openssl'
require 'hpricot'


#ALCHEMY

 file='C:\\Users\\ENTER USERNAME\\Desktop\\cloudsight.txt'
 f = File.open(file, "r")
 f.each_line {|line|

 tstart = 'name"=>"'
 tstop = '"'
 term = line[/#{tstart}(.*?)#{tstop}/m, 1]

 url = 'http://access.alchemyapi.com/calls'
 service = '/text/TextGetRankedTaxonomy'
 apikey = '?apikey=ENTER ALCHEMY API KEY'
 thething = '&text='
 termencoded = URI::encode(term)
 fullurl = url + service + apikey + thething + termencoded

 sleep 1
 opener = open(fullurl, 'Accept-Encoding' => '') {|f| f.read } 
 #print opener

I think I get the error at this point.

 lstart = '<label>/'
 lstop = '</label>'
 label = opener[/#{lstart}(.*?)#{lstop}/m, 1]

 sleep 1
 cstart = '<score>'
 cstop = '</score>'
 confidence = opener[/#{cstart}(.*?)#{cstop}/m, 1]

 #data = label + ',' + confidence + ',' + line
 print label
 print confidence
 print "\n"

 }

This is the error I seem to get:

C:/Ruby21/lib/ruby/2.1.0/uri/common.rb:304:in `escape': undefined method `gsub' for nil:NilClass (NoMethodError)

Any ideas as to how I can pass the error/escape it/ or make a string come up instead?

Upvotes: 0

Views: 127

Answers (2)

semiflex
semiflex

Reputation: 1246

I solved the problem. Turns out it's an issue on alchemys side in this instance. The taxonomy search just wasn't able to find a term

Upvotes: 0

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

I'm guessing the error is coming from this line:

termencoded = URI::encode(term)

And is probably happening because term is nil. Add some debugging to see what term is set to before that line is called. If you're okay with term being blank you could change that line to this:

termencoded = URI::encode(term.to_s)

Whether or not that's acceptable for your program I can't say.

I wouldn't try to suppress the error though. Something isn't working right and you should figure out what it is and how to handle it.

Upvotes: 0

Related Questions