Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Not Raising on Server Side errors #138

Open
djpate opened this issue Dec 9, 2022 · 1 comment
Open

Not Raising on Server Side errors #138

djpate opened this issue Dec 9, 2022 · 1 comment

Comments

@djpate
Copy link

djpate commented Dec 9, 2022

Hello,

I've been battling with an issue where the gem won't raise on a 500+ error.

Right now the gem raises on Timeout and Connection Failed I believe but If the response is a 500 or a 404 or 401 it automatically fallsback to an empty array which is not what I would expect since I'm not using the with_fallback option.

What is the best way to handle this?

@balvig
Copy link
Owner

balvig commented Dec 12, 2022

Hello @djpate, great question!

Out of the box, Spyke makes no assumptions about what to do with different status codes and only cares about the content of the hash passed in via Faraday:

{ data: { id: 1, name: 'Bob' }, metadata: {}, errors: {} }

This will raise a Spyke::ResourceNotFound if the hash doesn't contain an a primary key entry when finding a single record:

where(primary_key => id).find_one || raise(ResourceNotFound)

...or an empty array if trying to find multiple and not seeing any:

spyke/lib/spyke/http.rb

Lines 36 to 38 in 9d256d4

def new_collection_from_result(result)
Collection.new Array(result.data).map { |record| new_or_return(record) }, result.metadata
end

You can tweak your Faraday middleware to define custom behavior around specific http status codes.
For example something like this:

class Middleware::ErrorHandler < Faraday::Middleware
  def call(env)
    @app.call(env).on_complete do
      raise Spyke::ConnectionError, env[:body] unless env.success?
    end
  end
end

Hope that helps! Otherwise feel free to ask again 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants