Apartment ruby gem : Want to Catch an exception

1.9k views Asked by At

I am using this apartment a ruby gem.

I have add this in application.rb file:

config.middleware.use 'Apartment::Elevators::Subdomain'

When i try hit this in browser url 'test.domain.local:3000' where sub domain 'test' schema does not exist in PostgreSQL, i see this error

Apartment::SchemaNotFound (One of the following schema(s) is invalid: test, "public")

I know this is normal behavior of gem but want to catch this exception and redirect user to some other page, how can i do that?

1

There are 1 answers

1
Raccoon On

This is what I did:

Create file under lib/rescued_apartment_middleware.rb

module RescuedApartmentMiddleware
  def call(*args)
    begin
      super
    rescue Apartment::TenantNotFound
      Rails.logger.error "ERROR: Apartment Tenant not found: #{Apartment::Tenant.current.inspect}"
      return [404, {"Content-Type" => "text/html"}, ["#{File.read(Rails.root.to_s + '/public/404.html')}"] ]
    end
  end
end

and add to your Apartment initializer file following lines:

require 'rescued_apartment_middleware'

Rails.application.config.middleware.use 'Apartment::Elevators::Subdomain'
Apartment::Elevators::Subdomain.prepend RescuedApartmentMiddleware

This works like a charm! (Tested with ruby 2.1 and Rails 4.1)