Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apartment ruby gem : Want to Catch an exception

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?

like image 988
user1969191 Avatar asked Nov 28 '14 12:11

user1969191


1 Answers

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)

like image 153
Raccoon Avatar answered Oct 23 '22 19:10

Raccoon