CodeSampleX

Exemple

faraday 2.14.3: Handle Faraday JSON response deserialization and error middleware ordering without unparsed string payloads or type mutation traps

Échantillon vérifié pour gem faraday 2.14.3: Handle Faraday JSON response deserialization and error middleware ordering without unparsed string payloads or…

sha256:dfee68bbd326424c9c702d0cf42e9ddcaf36879dbd2f497a522dcfbc402a3938

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
2
Clés de signature qui l’ont compilé
2
Environnement déclaré ruby linux x64 ruby ruby rubygems

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
ruby 3 · linux debian/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · rubygems@1
2026-08-17
ruby 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · rubygems@1
2026-08-18

Cas

HOW
Objectif
Handle Faraday JSON response deserialization and error middleware ordering without unparsed string payloads or type mutation traps
Paquets
Symboles
  • Faraday.new
  • Faraday::Connection
  • Faraday::Response::Json
  • Faraday::Response::RaiseError
  • Faraday::Request::Json
Environnement
ruby
Créé
2026-08-17T02:38:41Z

Contrat

  1. Rescuing a client error from a Faraday connection with response :json declared before response :raise_error leaves error.response[:body] as an unparsed JSON String rather than a deserialized Hash because response middleware unwinds in reverse order.
  2. Declaring response :raise_error before response :json allows response :json to decode 4xx and 5xx payloads into Hashes before exceptions are raised.
  3. Symbol keys and Symbol values in request payloads are deserialized as String keys and String values after a JSON round trip unless symbolize_names parser option is configured.
  4. Empty response bodies and whitespace-only JSON responses deserialize to nil rather than empty Hashes or empty Strings.
  5. Responses with non-JSON Content-Type headers such as text/plain are left as raw Strings by response :json.
  6. Configuring preserve_raw: true stores the original raw JSON string in env[:raw_body] while env.body holds the parsed Hash.

Fichiers

  • Gemfile
  • Gemfile.lock
  • NOTES.md
  • csx.json
  • src/client.rb
  • test/contract.rb

Télécharger l’artefact source (tar.gz)

Code source

Gemfile
source "https://rubygems.org"

gem "faraday", "2.14.3"
gem "minitest", "5.27.0"
Gemfile.lock
GEM
  remote: https://rubygems.org/
  specs:
    faraday (2.14.3)
      faraday-net_http (>= 2.0, < 3.5)
      json
      logger
    faraday-net_http (3.4.4)
      net-http (~> 0.5)
    json (2.21.2)
    logger (1.7.0)
    minitest (5.27.0)
    net-http (0.9.1)
      uri (>= 0.11.1)
    uri (1.1.1)

PLATFORMS
  ruby
  x64-mingw-ucrt

DEPENDENCIES
  faraday (= 2.14.3)
  minitest (= 5.27.0)

CHECKSUMS
  bundler (4.0.18) sha256=02d9a17429de1847b4e0c9f27a9ee4b20c0a74c0a641b4e77195d6019e3618ac
  faraday (2.14.3) sha256=1882247e6766615c8220b4392bf1d27f6ebb63d8e28267587cef1fb0bf37f278
  faraday-net_http (3.4.4) sha256=0e78af151747ed1b00f33e25973b4bc220d7f16c00c39676817c8b12331eb588
  json (2.21.2) sha256=1f1d3b7cf2b3ba1a69beca0bb6db13d5438b80bff3cd54cdaaa620b9b07c1c6a
  logger (1.7.0) sha256=196edec7cc44b66cfb40f9755ce11b392f21f7967696af15d274dde7edff0203
  minitest (5.27.0) sha256=2d3b17f8a36fe7801c1adcffdbc38233b938eb0b4966e97a6739055a45fa77d5
  net-http (0.9.1) sha256=25ba0b67c63e89df626ed8fac771d0ad24ad151a858af2cc8e6a716ca4336996
  uri (1.1.1) sha256=379fa58d27ffb1387eaada68c749d1426738bd0f654d812fcc07e7568f5c57c6

BUNDLED WITH
  4.0.18
NOTES.md
# Faraday Response JSON Deserialization & Middleware Ordering

## What search_known_solution answered
`search_known_solution` returned hits for sample `sha256:39ce86a6452620096d83f2afd4e9efd34ee3307cb9e8a5be0a9d4c31a78b329f` (explicit Content-Type overrides disabling request JSON encoder), sample `sha256:c50f9bbfe83d4d0f5b44242b2e1675ffca6f3c29d43f04ddd3ac9e36f0f0ce46` (url_prefix leading slashes and params_encoder brackets), sample `sha256:2a72cabc0708deabd655105c3b93f320eeaeb23ab9a9d8fa709d9405824cc4fd` (request shape and v2 auth methods), and sample `sha256:79ed4575e23ad528e6582356a7d52176b0de0e0fe2073837ed92e98531487933` (v2 error namespaces). None covered the reverse response pipeline ordering trap between `response :json` and `response :raise_error` or deserialization type transformations.

## What a naive model would write instead
A naive model registers response middleware in intuitive reading order:
```ruby
conn = Faraday.new(url: "https://api.example.test") do |f|
  f.request :json
  f.response :json
  f.response :raise_error
end
```
and expects rescued error exceptions (`rescue Faraday::ClientError => e`) to contain deserialized Ruby Hashes in `e.response[:body]`, with `e.response[:body]["error"]` yielding the structured error message.

## How the wrong version fails
It fails silently in error handlers: `e.response[:body]` remains an unparsed JSON String because `raise_error` intercepts 4xx/5xx responses before `response :json` runs in Faraday's bottom-to-top response pipeline, causing String subscripting `["error"]` to return `"error"` rather than the error detail, and Symbol subscripting `[:error]` to raise `TypeError: no implicit conversion of Symbol into Integer`.
csx.json
{"case":{"believed":"Declaring response :json before response :raise_error in a Faraday connection ensures 4xx and 5xx error response bodies are deserialized into Ruby Hashes on rescued client and server exceptions.","caseId":"case:sha256:442f4ea3b14db0bda1ac75705341c89faa7a66a979892c9310283c2851b65da1","contract":["Rescuing a client error from a Faraday connection with response :json declared before response :raise_error leaves error.response[:body] as an unparsed JSON String rather than a deserialized Hash because response middleware unwinds in reverse order.","Declaring response :raise_error before response :json allows response :json to decode 4xx and 5xx payloads into Hashes before exceptions are raised.","Symbol keys and Symbol values in request payloads are deserialized as String keys and String values after a JSON round trip unless symbolize_names parser option is configured.","Empty response bodies and whitespace-only JSON responses deserialize to nil rather than empty Hashes or empty Strings.","Responses with non-JSON Content-Type headers such as text/plain are left as raw Strings by response :json.","Configuring preserve_raw: true stores the original raw JSON string in env[:raw_body] while env.body holds the parsed Hash."],"goal":"Handle Faraday JSON response deserialization and error middleware ordering without unparsed string payloads or type mutation traps","kind":"HOW","packages":["pkg:gem/faraday@2.14.3"],"schemaVersion":1,"symbols":["Faraday.new","Faraday::Connection","Faraday::Response::Json","Faraday::Response::RaiseError","Faraday::Request::Json"]},"contractCommand":["ruby","test/contract.rb"],"environment":{"arch":"x64","ecosystem":"gem","executionContext":"ruby","language":"ruby","os":"linux","packageManager":"rubygems","runtime":"ruby","schemaVersion":1},"license":"MIT-0","packages":["pkg:gem/faraday@2.14.3"],"schemaVersion":1,"symbols":["Faraday.new","Faraday::Connection","Faraday::Response::Json","Faraday::Response::RaiseError","Faraday::Request::Json"],"verifierAdapter":"rubygems@1"}
src/client.rb
require "faraday"

module ApiClient
  # Intuitive connection builder: declares response :json before response :raise_error.
  # TRAP: Because Faraday unwinds response middleware in reverse (bottom-to-top) order,
  # raise_error runs before response :json on 4xx/5xx responses, leaving error.response[:body]
  # as an unparsed JSON String instead of a deserialized Hash.
  def self.build_intuitive_connection(base_url: "https://api.example.test", stubs: nil)
    Faraday.new(url: base_url) do |f|
      f.request :json
      f.response :json
      f.response :raise_error
      f.adapter :test, stubs if stubs
    end
  end

  # Inverted connection builder: declares response :raise_error before response :json.
  # In the return pipeline, response :json executes first, decoding the response body
  # into a Hash before response :raise_error raises Faraday::ClientError/ServerError.
  def self.build_error_decoding_connection(base_url: "https://api.example.test", stubs: nil)
    Faraday.new(url: base_url) do |f|
      f.request :json
      f.response :raise_error
      f.response :json
      f.adapter :test, stubs if stubs
    end
  end

  # Advanced JSON connection builder with symbolize_names and preserve_raw enabled.
  def self.build_symbolized_connection(base_url: "https://api.example.test", stubs: nil)
    Faraday.new(url: base_url) do |f|
      f.request :json
      f.response :json, preserve_raw: true, parser_options: { symbolize_names: true }
      f.adapter :test, stubs if stubs
    end
  end
end
test/contract.rb
require "minitest/autorun"
require_relative "../src/client"

class FaradaySerializationBoundaryContract < Minitest::Test
  Stubs = Faraday::Adapter::Test::Stubs

  def setup
    @stubs = Stubs.new do |stub|
      # Echo endpoint returning JSON payload
      stub.post("/echo") do |env|
        [200, { "Content-Type" => "application/json" }, env.body]
      end

      # 204 No Content with empty body
      stub.delete("/items/1") do |env|
        [204, { "Content-Type" => "application/json" }, ""]
      end

      # Whitespace-only body under JSON Content-Type
      stub.get("/whitespace") do |env|
        [200, { "Content-Type" => "application/json" }, "   \r\n\t  "]
      end

      # Explicit JSON null literal
      stub.get("/null-literal") do |env|
        [200, { "Content-Type" => "application/json" }, "null"]
      end

      # Empty JSON object literal
      stub.get("/empty-object") do |env|
        [200, { "Content-Type" => "application/json" }, "{}"]
      end

      # JSON text returned with text/plain Content-Type
      stub.get("/plain-text-json") do |env|
        [200, { "Content-Type" => "text/plain" }, '{"status":"ok"}']
      end

      # 422 Unprocessable Entity error payload
      stub.post("/validate") do |env|
        [422, { "Content-Type" => "application/json" }, '{"error":"invalid_payload","code":42201}']
      end
    end
  end

  def test_intuitive_middleware_order_leaves_error_response_body_as_unparsed_string
    # TRAP: In Faraday's onion middleware pipeline, response handlers execute bottom-to-top.
    # When `f.response :json` is declared before `f.response :raise_error`, `raise_error`
    # intercepts the 4xx/5xx response before `response :json` has processed it.
    # As a result, error.response[:body] is a raw String, not a parsed Hash.
    conn = ApiClient.build_intuitive_connection(stubs: @stubs)

    err = assert_raises(Faraday::UnprocessableEntityError) do
      conn.post("/validate", { test: 1 })
    end

    assert_instance_of String, err.response[:body]
    assert_equal '{"error":"invalid_payload","code":42201}', err.response[:body]
    refute err.response[:body].is_a?(Hash)

    # String substring trap: on a String, indexing with ["error"] returns the substring "error"
    # rather than the value "invalid_payload", causing equality checks against field values to fail silently
    assert_equal "error", err.response[:body]["error"]
    refute_equal "invalid_payload", err.response[:body]["error"]

    # Indexing with a Symbol raises TypeError on String
    assert_raises(TypeError) do
      err.response[:body][:error]
    end
  end

  def test_inverted_middleware_order_parses_error_response_body_into_hash
    # By declaring `f.response :raise_error` before `f.response :json`, `response :json`
    # executes first on incoming responses, deserializing the body before `raise_error` fires.
    conn = ApiClient.build_error_decoding_connection(stubs: @stubs)

    err = assert_raises(Faraday::UnprocessableEntityError) do
      conn.post("/validate", { test: 1 })
    end

    assert_instance_of Hash, err.response[:body]
    assert_equal "invalid_payload", err.response[:body]["error"]
    assert_equal 42201, err.response[:body]["code"]
  end

  def test_symbol_keys_and_values_mutate_to_strings_on_round_trip
    # Ruby Symbols passed in request Hashes are serialized to JSON strings and
    # returned as String keys and values under default JSON response decoding.
    conn = ApiClient.build_intuitive_connection(stubs: @stubs)
    res = conn.post("/echo", { mode: :batch, retries: 3, tags: [:a, :b] })

    assert_equal 200, res.status
    assert_instance_of Hash, res.body
    assert res.body.key?("mode")
    refute res.body.key?(:mode)
    assert_nil res.body[:mode]
    assert_equal "batch", res.body["mode"]
    assert_equal ["a", "b"], res.body["tags"]
    assert_nil res.env[:raw_body]
  end

  def test_empty_and_whitespace_responses_decode_to_nil
    conn = ApiClient.build_intuitive_connection(stubs: @stubs)

    res_empty = conn.delete("/items/1")
    assert_equal 204, res_empty.status
    assert_nil res_empty.body

    res_ws = conn.get("/whitespace")
    assert_equal 200, res_ws.status
    assert_nil res_ws.body

    res_null = conn.get("/null-literal")
    assert_equal 200, res_null.status
    assert_nil res_null.body

    res_obj = conn.get("/empty-object")
    assert_equal 200, res_obj.status
    assert_equal({}, res_obj.body)
  end

  def test_non_json_content_type_remains_raw_string
    conn = ApiClient.build_intuitive_connection(stubs: @stubs)
    res = conn.get("/plain-text-json")

    assert_equal 200, res.status
    assert_instance_of String, res.body
    assert_equal '{"status":"ok"}', res.body
  end

  def test_symbolize_names_and_preserve_raw_options
    conn = ApiClient.build_symbolized_connection(stubs: @stubs)
    res = conn.post("/echo", { user_id: 100, role: :admin })

    assert_equal 200, res.status
    assert_instance_of Hash, res.body
    assert res.body.key?(:user_id)
    assert_equal 100, res.body[:user_id]
    assert_equal "admin", res.body[:role]
    refute res.body.key?("user_id")

    # preserve_raw: true stores the unparsed JSON String in env[:raw_body]
    assert_equal '{"user_id":100,"role":"admin"}', res.env[:raw_body]
  end
end

Seeder d'origine

csx-seed