Skip to content

Instantly share code, notes, and snippets.

@EdwardIII

EdwardIII/obj.rb Secret

Created February 19, 2016 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EdwardIII/f828d693d9cebe249866 to your computer and use it in GitHub Desktop.
Save EdwardIII/f828d693d9cebe249866 to your computer and use it in GitHub Desktop.
module Api
class ApiError < StandardError
attr_reader :response_body
def initialize(response_body)
throw "Sorry, send response body hash" unless response_body.is_a? ::Hash
@response_body = response_body
super(to_s) if error_infos
end
def error_infos
Hash.include Api::CoreExtensions::Hash::Deep
@response_body.values_at_deep :error_info
end
def raise_if_needed
raise self if error_infos.any?
end
def to_s
error_infos.map do |m|
"[#{m[:error_code]}] #{m[:error_message]} #{m[:error_data]}"
end.join(', ')
end
end
end
require 'test_helper'
module Api
class ApiErrorTest < ActiveSupport::TestCase
def response_body
{
"body" =>
[
{:error_info =>
{
:error_code => 123,
:error_message => "First error",
:error_data => "payload1"
},
},
{:error_info =>
{
:error_code => 234,
:error_message => "Second error",
:error_data => "payload2"
}
}
]
}
end
test "stringifies nicely" do
ex = Api::ApiError.new(response_body)
assert_equal "[123] First error payload1, [234] Second error payload2", ex.to_s
end
test "raises if needed" do
ex = Api::ApiError.new(response_body)
assert_raises(Api::ApiError) {
ex.raise_if_needed
}
end
test "accepts only hashes" do
ex = assert_raises(Exception) { ApiError.new("normal string message") }
assert ex.message.include? "hash"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment