Kenn
Kenn

Reputation: 189

Unable to rescue ActionController::UnknownFormat for formats I don't use

I'm joining the many people who want to rescue ActionController::UnknownFormat in their Rails applications but are unable to.

I'd prefer to rescue exceptions I don't care about, both to provide better error pages to misguided uses, and also to keep my exception tracker quiet.

The two cases I'm trying to solve are:

  1. URLs like /catalog.xml (I only respond to HTML requests)
  2. Requests with restrictive formats, such as: variant. request.formats: ["application/json", "text/javascript", "application/xml"] (usually bots)

The research I've done turned up this solution as the best approach but, unfortunately, it doesn't work for me.

In app/controllers/application_controller.rb, I have this:

rescue_from ActiveRecord::RecordNotFound,               :with => :render_standard_error
rescue_from ActionController::UnknownFormat,            :with => :render_standard_error
rescue_from ActionController::InvalidAuthenticityToken, :with => :render_token_error

This works great, except for that ActionController::UnknownFormat.

The render_standard_error method just sets up some env defaults and renders an error page.

I expected that rescue_from ActionController::UnknownFormat would work the way it works for the other error types but the exception is not being caught.

I'm sure I'm missing something terribly obvious here but damned if I can figure it out.

I'm using Rails 5.2.2 with Passenger 5.3.1.

Update:

I'm actually seeing two different behaviors:

  1. When I go to /catalog.xml, I get:
ActionController::UnknownFormat at /catalog.xml
ProductsController#index is missing a template for this request format and variant.

request.formats: ["application/xml"]
request.variant: []
  1. But if I try /catalog.invalid, the catalog page loads normally, as if I had used just /catalog.

Upvotes: 1

Views: 407

Answers (1)

BenKoshy
BenKoshy

Reputation: 35595

I could not replicate your problem. Here's what I tried:

  1. Spun up a new rails app.
  2. I created a Person scaffold (with name as the only columns). Then I ran the migrations.
  3. Then I pasted the following in my application controller:

Stack Overflow could not get the formatting right so I pasted it here: https://gist.github.com/BKSpurgeon/391b0da243b32936334d7989f3e3cadb

Seems to raise and catch the exception just fine?! Please post more information: where are you expecting to raise the error.

Steps

  • Are you able to manually throw and catch the exception?
  • Rails might do some funny things: if you ask for a format that doesn't exist, rails might trip another exception. Are you able to add a byebug statement in the controller where you are expecting to fall, and then watch it all the way through?

Upvotes: 1

Related Questions