Skip to content

Instantly share code, notes, and snippets.

@linqueta
Last active December 24, 2019 17:52
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 linqueta/32bf5c12f23d2cb3e8d456e468892943 to your computer and use it in GitHub Desktop.
Save linqueta/32bf5c12f23d2cb3e8d456e468892943 to your computer and use it in GitHub Desktop.
Handling resource not found errors using after hook
require 'eezee'
require 'initializer'
require 'character'
# In Rick and Morty api we can get all characters through this route: https://rickandmortyapi.com/api/character/
# but, if we call to show a character like https://rickandmortyapi.com/api/character/900 and it doesn't exist, will returned
# a HTTP code 404.
# It's known if we call the route https://rickandmortyapi.com/api/character/a will be returned a HTTP code 500
# This character exists
RickMorty::Character.find!(1).body
# => {:id=>1, :name=>"Rick Sanchez", :status=>"Alive", :speci...
# This character doesn't exist, but how we handled not found errors in after hook,
# it won't raise any exception
RickMorty::Character.find!(900).body
# => {:error=>"Character not found"}
# This character doesn't exist, but how we didn't handle internal server errors in after hook,
# it'll raise a Eezee::InternalServerError
RickMorty::Character.find!(900).body
# => Eezee::InternalServerError (CODE: 500 - BODY: {"error":"Hey! that parameter is not allowed, try with a number instead ;)"})
module RickMorty; end
module RickMorty::Character
extend Eezee::Client
eezee_service :rick_and_morty_api
eezee_request_options path: 'character/:character_id'
module_function
def find!(id)
get(
params: { character_id: id },
after: ->(_req, _res, err) { err.is_a?(Eezee::ResourceNotFoundError) }
)
end
end
Eezee.configure do |config|
config.add_service :rick_and_morty_api,
url: 'rickandmortyapi.com/api',
protocol: :https,
raise_error: true,
logger: true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment