使用HTTParty我遇到了无法正确捕获auth错误的情况,因为JSON或XML解析器拦截了“HTTP Basic:Access denied”。响应。
这是我的代码:
要求'rubygems' 要求'httparty'
class Client
include HTTParty
def initialize(host, user, password)
self.class.base_uri host
self.class.basic_auth user, password
end
def get(base_path, data_format)
self.class.get("#{base_path}.#{data_format}")
end
end
cl = Client.new('host.com', 'useranme', 'password')
p cl.get('/resource_path', 'json')
运行此操作,如果用户名或密码错误,我收到以下错误:
/home/ayurchuk/.rvm/rubies/ruby-1.9.3-p0/lib/ruby/1.9.1/json/common.rb:148:in `parse': 743: unexpected token at 'HTTP Basic: Access denied. (MultiJson::DecodeError)
'
from /home/ayurchuk/.rvm/rubies/ruby-1.9.3-p0/lib/ruby/1.9.1/json/common.rb:148:in `parse'
from /home/ayurchuk/.rvm/gems/ruby-1.9.3-p0@uitests/gems/multi_json-1.0.4/lib/multi_json/engines/json_common.rb:9:in `decode'
from /home/ayurchuk/.rvm/gems/ruby-1.9.3-p0@uitests/gems/multi_json-1.0.4/lib/multi_json.rb:76:in `decode'
from /home/ayurchuk/.rvm/gems/ruby-1.9.3-p0@uitests/gems/httparty-0.8.1/lib/httparty/parser.rb:116:in `json'
from /home/ayurchuk/.rvm/gems/ruby-1.9.3-p0@uitests/gems/httparty-0.8.1/lib/httparty/parser.rb:136:in `parse_supported_format'
...
在解析器获得响应之前是否有任何可能的方法来捕获这些auth错误?
答案 0 :(得分:1)
我不是说这是最理想的解决方案,但你可以快速修补它。错误来自HTTParty的Parser类,它在MultiJson上调用不安全的方法而不处理可能的错误。
我刚刚在初始化程序中删除了以下内容,这允许我移动检查这些响应,查找401状态代码,这实际上就是您所需要的。
module HTTParty
class Parser
protected
def json
if MultiJson.respond_to?(:adapter)
MultiJson.load(body) rescue {}
else
MultiJson.decode(body) rescue {}
end
end
end
end