How to rescue custom exceptions coming from a middleware in Rails 3.2?

Viewed 3324

I have a Rails 3.2 application that uses Apartment, which is used as a middleware. Apartment throws an Apartment::SchemaNotFound exception and there is no way to rescue it with rescue_from from the ApplicationController. I thought I'd use config.exceptions_app as described in point #3 in this blog post, but I can't set the router as the exception app, I assume I have to create my own.

So the question is: How do I proceed?

2 Answers

We've purposefully left Apartment pretty minimal to allow you the handle the exception itself without really needing any Rails specific setup.

I'd do something similar to what @jenn is doing above, but I wouldn't bother setting a rack env and dealing with it later, just handle the response completely in rack.

It's typical for instance that you maybe just want to redirect back to / on SchemaNotFound

You could do something like

module MyApp
  class Apartment < ::Apartment::Elevators::Subdomain
    def call(env)
      super
    rescue ::Apartment::TenantNotFound
      [302, {'Location' => '/'}, []]
    end
  end
end

This is a pretty raw handling of the exception. If you need something to happen more on the Rails side, then @jenn's answer should also work.

Check out the Rack for more details

Related