如果响应主体不在JSON中,如何避免解析JSON,否则会抛出一个巨大的异常,我想处理
def execute_method(foo)
...
response = self.class.get("/foo.php", query: query)
JSON.parse(response.body)
end
正如@Anthony指出的那样,请使用begin / rescue。
begin
...
JSON.parse(response.body)
rescue JSON::ParserError
# Handle error
end
更新资料
要检查字符串是否为有效的json,可以创建一个方法:
def valid_json?(string)
!!JSON.parse(string)
rescue JSON::ParserError
false
end
valid_json?("abc") #=> false
valid_json?("{}") #=> true
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句