Apartment ruby gem : Want to Catch an exception
Asked Answered
A

1

13

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?

Albertson answered 28/11, 2014 at 12:12 Comment(0)
T
17

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)

Thompson answered 30/1, 2015 at 10:28 Comment(1)
FYI Apartment::DatabaseNotFound, Apartment::SchemaNotFound can be replaced with Apartment::TenantNotFound. Those other exceptions are deprecated.Crinkly

© 2022 - 2024 — McMap. All rights reserved.