Skip to content

Instantly share code, notes, and snippets.

@mxmzb
Created April 23, 2015 17:20
Show Gist options
  • Save mxmzb/da0e8d4bec91c9b48be3 to your computer and use it in GitHub Desktop.
Save mxmzb/da0e8d4bec91c9b48be3 to your computer and use it in GitHub Desktop.
Faraday exception handling
# lib/faraday/steam_api_exceptions.rb
class SteamApiExceptions < Faraday::Middleware
def call(env)
begin
@app.call(env)
raise "this will be actually entered if everything is correct"
rescue => e
raise "this should be called, shouldn't it?"
end
end
end
# lib/steam/steam_api.rb
class SteamApi
@steam_api_connection = Faraday.new(:url => 'https://api.steampowered.com', request: {
open_timeout: 5, # opening a connection
timeout: 2 # waiting for response
}) do |connection|
connection.request :url_encoded # form-encode POST params
connection.response :logger # log requests to STDOUT
connection.adapter Faraday.default_adapter # make requests with Net::HTTP
connection.use SteamApiExceptions
end
# i am calling this method
def self.get_steam_avatar(steam_id, size)
response = @steam_api_connection.get "/ISteamUser/GetPlayerSummaries/v0002/?steamids=#{steam_id}&key=#{ENV['STEAM_WEB_API_KEY']}"
if size == 64
key = "avatarmedium"
elsif size == 184
key = "avatarfull"
else
key = "avatar"
end
JSON.parse(response.body)["response"]["players"][0][key]
end
end
# the error if i turn off internet
Faraday::ConnectionFailed at /
getaddrinfo: nodename nor servname provided, or not known
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment