lagotto / alm-report

ALM Reports
http://almreports.plos.org/
MIT License
8 stars 3 forks source link

Faraday error handling #86

Open mfenner opened 10 years ago

mfenner commented 10 years ago
2014-10-29 12:44:39.386 [FATAL] Faraday::ParsingError (757: unexpected token at '<html><body><h1>504 Gateway Time-out</h1>
The server didn't respond in time.
</body></html>
'):
  app/models/search_crossref.rb:51:in `get'
  app/models/search_result.rb:16:in `from_crossref'
  app/models/search_result.rb:26:in `block in from_cache'
  app/models/search_result.rb:25:in `from_cache'
  app/controllers/reports_controller.rb:157:in `block in prepare_visualization_data'
  app/controllers/reports_controller.rb:156:in `prepare_visualization_data'
  app/controllers/reports_controller.rb:201:in `multiple_documents_visualizations'
  app/controllers/reports_controller.rb:99:in `visualizations'
  app/controllers/application_controller.rb:42:in `save_session_dois' (pid:25371)
Faraday::ParsingError (757: unexpected token at '<html><body><h1>503 Service Unavailable</h1>
No server is available to handle this request.
</body></html>
'):
  app/models/search_crossref.rb:51:in `get'
2014-10-29 11:39:14.393 [FATAL] MultiJson::ParseError (795: unexpected token at 'alihack<%eval request("alihack.com")%> '):
  json (1.8.1) lib/json/common.rb:155:in `parse'
mfenner commented 10 years ago

I use this approach (https://github.com/articlemetrics/lagotto/blob/master/app/models/concerns/networkable.rb#L198-L216):

def parse_error_response(string)
      if is_json?(string)
        string = JSON.parse(string)
      elsif is_xml?(string)
        string = Hash.from_xml(string)
      end
      string = string['error'] if string.is_a?(Hash) && string['error']
      string
    end

    def is_xml?(string)
      Nokogiri::XML(string).errors.empty?
    end

    def is_json?(string)
      JSON.parse(string)
    rescue JSON::ParserError
      false
    end
  end