gpt4 book ai didi

ruby - 如何处理 ruby​​ 中的 JSON 解析器错误

转载 作者:数据小太阳 更新时间:2023-10-29 06:40:38 24 4
gpt4 key购买 nike

如果响应主体不是 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

关于ruby - 如何处理 ruby​​ 中的 JSON 解析器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27944050/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com