Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No implicit conversion of HTTParty::Response into String

Tags:

json

ruby

When I am trying to parse some kind of response into JSON I am getting the following error. I have raised JSON::ParserError in my code if incase parsing fails. But this kind of exception does not come under this parser error. I don't know why this kind of error is thrown? and How to rescue this error?

code:

 begin
   parsed_response = JSON.parse(response)
 rescue JSON::ParserError => e
   nil
 end

Error:

A TypeError occurred in background at 2014-11-16 03:01:08 UTC :

  no implicit conversion of HTTParty::Response into String
like image 558
Sam Avatar asked Nov 17 '14 07:11

Sam


1 Answers

The error you're getting is a TypeError. It's raised when you pass the wrong kind of argument to certain methods. You can rescue it like this:

# not ideal - see below
begin
  parsed_response = JSON.parse(response)
rescue JSON::ParserError, TypeError => e
  puts e
end

I wouldn't recommend this, though. The reason you're getting a TypeError is that JSON.parse requires a String object, and you've passed it a HTTParty::Response object. Try giving it a String object instead. e.g.:

# better
parsed_response = JSON.parse(response&.body || "{}")

This way, a nil value in either response or response.body returns a usable object. In this example, the object is an empty Hash, though you can replace the JSON string with whatever value you want to represent a "nothing there" value (e.g. "[]" or "null").

like image 69
user513951 Avatar answered Sep 26 '22 13:09

user513951