Skip to content

Commit

Permalink
add exception handling to ip_info (#95)
Browse files Browse the repository at this point in the history
This adds exception handling for when ip info look ups fail for whatever
reason. See:

https://rollbar.com/railslink/railslink/items/25/
https://rollbar.com/railslink/railslink/items/26/
  • Loading branch information
phallstrom committed Apr 17, 2019
1 parent 2fbade8 commit 58c46ba
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
6 changes: 5 additions & 1 deletion app/models/ip_info.rb
Expand Up @@ -4,7 +4,11 @@
class IpInfo
def initialize(ip_address)
@ip_address = ip_address
@info = JSON.parse(Net::HTTP.get("ip-api.com", "/json/#{@ip_address}"))
Timeout::timeout(3) do
@info = JSON.parse(Net::HTTP.get("ip-api.com", "/json/#{@ip_address}"))
end
rescue Net::OpenTimeout, JSON::ParserError, Timeout::Error
@info = {}
end

def successful?
Expand Down
19 changes: 19 additions & 0 deletions spec/models/ip_info_spec.rb
@@ -1,6 +1,25 @@
require 'rails_helper'

RSpec.describe IpInfo, type: :model do
context "exceptions" do
let(:subject) { described_class.new("73.11.237.17") }

it "is unsuccessful when the network times out" do
allow(Net::HTTP).to receive(:get).and_raise(Net::OpenTimeout)
expect(subject.successful?).to eq false
end

it "is unsuccessful when the json is invalid" do
allow(Net::HTTP).to receive(:get).and_return("") # invalid JSON
expect(subject.successful?).to eq false
end

it "is unsuccessful when the timeout is reached" do
allow(Net::HTTP).to receive(:get).and_raise(Timeout::Error)
expect(subject.successful?).to eq false
end
end

context "invalid ip addresses" do
let(:subject) { described_class.new("invalid") }

Expand Down

0 comments on commit 58c46ba

Please sign in to comment.