Skip to content

Present errors with an entity that has a root - #3117

Open
Asimmirzac wants to merge 3 commits into
ruby-grape:masterfrom
Asimmirzac:present-errors-with-entity-root
Open

Asimmirzac wants to merge 3 commits into
ruby-grape:masterfrom
Asimmirzac:present-errors-with-entity-root

Conversation

@Asimmirzac

Copy link
Copy Markdown

Fixes #1870.

Grape::Entity.represent returns a Hash wrapping the entity when the entity declares a root. The error formatter called serializable_hash on that Hash, which raised NoMethodError, so the client got a 500 in place of the status given to error!:

class ErrorEntity < Grape::Entity
  root 'errors', 'error'
  expose :code
end

error!({ code: 408, with: ErrorEntity }, 408) # answered 500, now 408 {"error":{"code":408}}

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_entity integration 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

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>
@Asimmirzac
Asimmirzac force-pushed the present-errors-with-entity-root branch from 2ec0386 to 04e5b13 Compare November 30, 2026 09:26

@ericproulx ericproulx left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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::Presenter work as an error presenter too.
  • The specs need a copy under spec/grape/, since bundle exec rake skips spec/integration.

Comment thread lib/grape/error_formatter/base.rb Outdated

# An entity that declares a +root+ is represented by a Hash wrapping it
# rather than by the entity itself.
def serialize(representation)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
end

With 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.

Comment thread lib/grape/error_formatter/base.rb Outdated
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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread lib/grape/error_formatter/base.rb Outdated
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 the failure entity doesn't describe
  • txt: Ruby Hash#inspect strings, 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?

Comment thread lib/grape/error_formatter/base.rb Outdated
return representation.transform_values { |value| serialize(value) } if representation.is_a?(Hash)
return representation.map { |value| serialize(value) } if representation.is_a?(Array)

representation

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
@Asimmirzac

Copy link
Copy Markdown
Author

Thanks for the detailed review. Pushed 0c3013e:

  • The helper is now serializable_representation, so a custom formatter's own serialize is called with the finished message again (custom:{"code":408}). There is a spec for that.
  • The embeds are passed as keywords, so error!({ code: 408, with: Grape::Presenters::Presenter }, 408) answers 408 {"code":408}.
  • An entity collection without a root stays unsupported. Only an entity or a Hash is accepted; anything else, such as an Array, nil or a String, raises a TypeError naming the presenter, so it is logged and answers 500 as before. Inside the Hash, an Array is mapped only when every element responds to serializable_hash, the same as Grape::Formatter::SerializableHash. I kept the two helpers separate, as sharing one would also touch the success path.
  • Specs are added in spec/grape/error_formatter/base_spec.rb with a plain presenter, for format :json, :xml and :txt. For XML, a root named error renders <error><error><code ...>408</code></error></error>. The spec records that as it is now; I can change it if you want a different shape.

The full suite (3397 examples), the grape_entity specs and RuboCop pass on Ruby 3.4.

Prepared with AI assistance (Claude Code).

@ericproulx

Copy link
Copy Markdown
Contributor

Thanks @Asimmimx , could you fix the merge conflict. I'll run CI after that. Cheers

@Asimmirzac

Copy link
Copy Markdown
Author

Merged master in 5c3f1a0; the only conflict was the CHANGELOG entry, now between #3114 and #3118. The code is unchanged.

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

Successfully merging this pull request may close these issues.

NoMethodError: undefined method `serializable_hash' for #<Hash:0x00007fc3ef69c278> when error entity has root

2 participants