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
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"
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With