module Jekyll::Algolia::ErrorHandler

def self.error_hash(message)

by our error matchers
Returns a hash of all parts of the message, to be more easily consumed

message - The raw message as returned by the API

Public: Parses an Algolia error message into a hash of its content
def self.error_hash(message)
  message = message.delete("\n")
  # Ex: Cannot PUT to https://appid.algolia.net/1/indexes/index_name/settings:
  # {"message":"Invalid Application-ID or API key","status":403} (403)
  regex = VerEx.new do
    find 'Cannot '
    capture('verb') { word }
    find ' to '
    capture('scheme') { word }
    find '://'
    capture('application_id') { word }
    anything_but '/'
    find '/'
    capture('api_version') { digit }
    find '/'
    capture('api_section') { word }
    find '/'
    capture('index_name') do
      anything_but('/')
    end
    find '/'
    capture do
      capture('api_action') { word }
      maybe '?'
      capture('query_parameters') do
        anything_but(':')
      end
    end
    find ': '
    capture('json') do
      find '{'
      anything_but('}')
      find '}'
    end
    find ' ('
    capture('http_error') { word }
    find ')'
  end
  matches = regex.match(message)
  return false unless matches
  # Convert matches to a hash
  hash = {}
  matches.names.each do |name|
    hash[name] = matches[name]
  end
  hash['api_version'] = hash['api_version'].to_i
  hash['http_error'] = hash['http_error'].to_i
  # Merging the JSON key directly in the answer
  hash = hash.merge(JSON.parse(hash['json']))
  hash.delete('json')
  # Merging the query parameters in the answer
  CGI.parse(hash['query_parameters']).each do |key, values|
    hash[key] = values[0]
  end
  hash.delete('query_parameters')
  hash
end