2012-01-12 74 views
1

使用HTTParty由于JSON或XML解析器拦截“HTTP基本:访问被拒绝”,我遇到了无法正确捕获身份验证错误的情况。响应。HTTParty。在使用JSON/XML解析器解析响应之前捕获身份验证错误

这里是我的代码:

需要 '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/[email protected]/gems/multi_json-1.0.4/lib/multi_json/engines/json_common.rb:9:in `decode' 
    from /home/ayurchuk/.rvm/gems/[email protected]/gems/multi_json-1.0.4/lib/multi_json.rb:76:in `decode' 
    from /home/ayurchuk/.rvm/gems/[email protected]/gems/httparty-0.8.1/lib/httparty/parser.rb:116:in `json' 
    from /home/ayurchuk/.rvm/gems/[email protected]/gems/httparty-0.8.1/lib/httparty/parser.rb:136:in `parse_supported_format' 
    ... 

解析器得到响应之前是否有任何可能的方法来捕获这些认证错误?

回答

1

我并不是说这是最理想的解决方案,但是您可以快速将猴子补丁。该错误来自HTTParty的解析器类,它调用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