Repository navigation
Present errors with an entity that has a root - #3117
Asimmirzac wants to merge 3 commits into
Conversation
Grape::Entity.represent returns a Hash wrapping the entity when the entity declares a root, so the error formatter called serializable_hash on a Hash and raised NoMethodError. The client got a 500 in place of the status error! asked for. Fixes ruby-grape#1870. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2ec0386 to
04e5b13
Compare
ericproulx
left a comment
There was a problem hiding this comment.
Thanks for tracking this down. The fix works: on this branch, an error! presented with an entity that has a root answers its status in txt, json, xml and problem+json, where each answered 500 before.
A few things before merging, inline:
- The new helper's name can collide with a custom formatter's own
serialize. This is the one blocker. - While on this line, passing the embeds as keywords would let
Grape::Presenters::Presenterwork as an error presenter too. - The specs need a copy under
spec/grape/, sincebundle exec rakeskipsspec/integration.
|
|
||
| # An entity that declares a +root+ is represented by a Hash wrapping it | ||
| # rather than by the entity itself. | ||
| def serialize(representation) |
There was a problem hiding this comment.
present calls this with an implicit receiver, so a custom error formatter that subclasses Base and has its own private serialize now gets the entity here, instead of the finished message:
class MyFormatter < Grape::ErrorFormatter::Base
class << self
def format_structured_message(message) = serialize(message)
private
def serialize(message) = "custom:#{Grape::Json.dump(message)}"
end
endWith error!({ code: 408, with: SomeEntity }, 408), master answers custom:{"code":408} and this branch answers custom:{"message":"custom:{\"code\":408}"}. A less common name, such as serializable_representation, avoids that.
This also nearly repeats Grape::Formatter::SerializableHash.serialize, which already differs on Arrays: it maps only when every element responds to serializable_hash. If both shared one helper, success and error bodies would serialize the same way.
| embeds = { env: } | ||
| embeds[:version] = env[Grape::Env::API_VERSION] if env.key?(Grape::Env::API_VERSION) | ||
| presenter.represent(payload, embeds).serializable_hash | ||
| serialize(presenter.represent(payload, embeds)) |
There was a problem hiding this comment.
Not from this PR, but it's the same line: represent(payload, embeds) passes the embeds as a positional Hash, and Grape::Presenters::Presenter.represent(object, **_options) takes keywords only. So error!({ code: 408, with: Grape::Presenters::Presenter }, 408) still raises ArgumentError and answers 500. The success path calls represent(object, env:, **options). presenter.represent(payload, **embeds) would work for both, since grape-entity's represent(objects, options = {}) takes keywords too.
| def serialize(representation) | ||
| return representation.serializable_hash if representation.respond_to?(:serializable_hash) | ||
| return representation.transform_values { |value| serialize(value) } if representation.is_a?(Hash) | ||
| return representation.map { |value| serialize(value) } if representation.is_a?(Array) |
There was a problem hiding this comment.
An entity collection without a root used to answer 500. This branch lets it through, and each formatter gives it a different shape. With desc 'd', failure: [[408, 'x', NoRootEntity]] and error!([{ code: 1 }, { code: 2 }], 408):
- json:
{"error":[{"code":1},{"code":2}]}, an envelope thefailureentity doesn't describe - txt: Ruby
Hash#inspectstrings, which change between Ruby versions - problem+json: an Array in
detail, which RFC 9457 defines as a string
Could you either pick a shape for it and add a spec, or keep it unsupported?
| return representation.transform_values { |value| serialize(value) } if representation.is_a?(Hash) | ||
| return representation.map { |value| serialize(value) } if representation.is_a?(Array) | ||
|
|
||
| representation |
There was a problem hiding this comment.
With .serializable_hash, a presenter that returned something unexpected raised, and the error was logged. Now nil or a String falls through. A presenter returning nil answers 408 {"error":null} with nothing logged, and one returning a JSON String gets encoded twice. Could anything that isn't serializable, a Hash or an Array raise here, so a broken presenter still shows up?
| end | ||
| end | ||
|
|
||
| context 'when the presenter has a root' do |
There was a problem hiding this comment.
bundle exec rake skips spec/integration (the Rakefile's exclude_pattern), so only the grape_entity CI job runs these. The bug doesn't need grape-entity: a plain presenter whose represent returns { error: object } reproduces it, so a spec under spec/grape/ would run in every job.
These specs also leave format unset, so they go through Txt's JSON fallback. Covering format :json and format :xml would exercise Json#wrap_message as well. In XML, a root named error renders <error><error>…</error></error>, which deserves a spec if it's intended.
…r representations - Rename the helper to serializable_representation, so it does not replace a custom formatter's own serialize. - Pass the embeds as keywords, so Grape::Presenters::Presenter works as an error presenter. - Keep entity collections without a root unsupported and raise for anything that is not an entity or a Hash. - Add specs under spec/grape/ for json, xml and txt. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Thanks for the detailed review. Pushed 0c3013e:
The full suite (3397 examples), the grape_entity specs and RuboCop pass on Ruby 3.4. Prepared with AI assistance (Claude Code). |
|
Thanks @Asimmimx , could you fix the merge conflict. I'll run CI after that. Cheers |
…ity-root # Conflicts: # CHANGELOG.md
Fixes #1870.
Grape::Entity.representreturns a Hash wrapping the entity when the entity declares aroot. The error formatter calledserializable_hashon that Hash, which raisedNoMethodError, so the client got a 500 in place of the status given toerror!:The same happened for an entity named by
failure. The representation is now serialized through Hashes and Arrays, so collections under the plural root work too. Entities without a root are serialized as before.The new specs fail without the change. The full RSpec suite and the
grape_entityintegration specs pass on Ruby 3.4.13, and RuboCop is clean on the changed files.Prepared with AI assistance (Claude Code, Claude Opus 5.5).
🤖 Generated with Claude Code