Skip to content

Return 406 Not Acceptable for malformed Accept headers - #181

Merged
jrhoads merged 3 commits into
masterfrom
invalid-accept-headers
Jul 15, 2026
Merged

jrhoads merged 3 commits into
masterfrom
invalid-accept-headers

Conversation

@jrhoads

@jrhoads jrhoads commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

Purpose

Handle malformed or invalid Accept headers so the API returns a clean 406 Not Acceptable response instead of raising an unhandled ActionDispatch::Http::MimeNegotiation::InvalidType error.

Approach

Add a custom Rack middleware that intercepts ActionDispatch::Http::MimeNegotiation::InvalidType before it propagates through the Rails instrumentation stack, and return a short plain-text error message.

Key Modifications

  • Added config/initializers/catch_invalid_mime_type.rb defining CatchInvalidMimeTypeMiddleware.
  • Inserted the middleware into the Rails stack after ActionDispatch::DebugExceptions.
  • Added a request spec in spec/api/api_spec.rb for a malformed Accept header (application/json, *).
  • Added the corresponding VCR cassette fixture for the test.

Important Technical Details

  • ActionDispatch::Http::MimeNegotiation::InvalidType is raised inside ActionController::Instrumentation#process_action, which occurs before rescue_from callbacks run, so a middleware layer is the appropriate place to handle it.
  • The middleware returns [406, { "Content-Type" => "text/plain" }, [RESPONSE_BODY]].
  • Catching the exception inside DebugExceptions prevents noisy multi-line backtraces from being logged.
  • The middleware is inserted after ActionDispatch::DebugExceptions so the exception can be handled cleanly before reaching the debug error page.

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)

Reviewer, please remember our guidelines:

  • Be humble in the language and feedback you give, ask don't tell.
  • Consider using positive language as opposed to neutral when offering feedback. This is to avoid the negative bias that can occur with neutral language appearing negative.
  • Offer suggestions on how to improve code e.g. simplification or expanding clarity.
  • Ensure you give reasons for the changes you are proposing.

@jrhoads
jrhoads merged commit a5572e3 into master Jul 15, 2026
1 check passed
@jrhoads
jrhoads deleted the invalid-accept-headers branch July 15, 2026 15:35
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.

2 participants