简体   繁体   中英

The response “er ?” is getting intermittently for Ruby http request

I am running a http request by using the open-uri method. The following error message is intermittently getting rather than the expected output.

An error of type NoMethodError happened, message is undefined method `[]' for nil:NilClass

er ?

And my code is given below,

request_uri = "my url here"
request_query = ''
url = "#{request_uri}#{request_query}"

begin
  buffer = open(request_uri,
             'app-key' => ENV['API_KEY'],
             'app-token' => ENV['API_TOKEN'],
             'trail-Token' => ENV['TRAIL_TOKEN']).read
  parsed = JSON.parse(buffer)
  events = parsed['events']
  event = Array(events).last
  message = event['message']
  otp = message[-5,4]
  print "otp", otp
rescue Exception => ex
  puts "An error of type #{ex.class} happened, message is #{ex.message}"
  retry
end

puts "otp returned", otp

Since I am new to ruby don't know why the response is getting like this. Once I get the response properly the next time when I run the script er ? is the response. Someone please give a helping hand to fix the issue.

The begin rescue block is pretty big here, you are losing your exception details, including linenumbers.

Effectively, at some point what is happening is you are calling [] on an object that is nil, and it fails. Which point? You wont be able to see without the stack trace or a smaller block.

As @Stefan mentioned, please dont catch exception, if you are not sure what you will get, leave it blank and ruby will do the best thing for you and grab the right part of the exception traces, it just makes life hard, see: Why is it a bad style to `rescue Exception => e` in Ruby?

If you wanna see the exact line that the exception is caused on, and I would also definitely limit retries.

begin
  retries ||= 0
  ...

rescue => ex
  puts "An error of type #{ex.class} happened, message is #{ex.message}"
  puts ex.backtrace
  retry if (retries += 1) < 3
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM