John Topley
John Topley

Reputation: 115362

Error handlers don't run in modular Sinatra app

I have a Sinatra application that uses the modular style. Everything works fine apart from my error handler blocks which don't get invoked. Here's the relevant code:

app.rb

require_relative './routes/base'
require_relative './routes/routing'

module Example
  class App < Sinatra::Application
    use Routes::Base
    use Routes::Routing
  end
end

base.rb

require 'sinatra/base'

module Example
  module Routes
    class Base < Sinatra::Application
      configure do

        # etc.
      end

      # Error pages.
      error 404 do  # <- Doesn't get invoked.
        erb :not_found
      end

      error 500 do  # <- Doesn't get invoked.
        erb :internal_server_error
      end
    end
  end
end

routing.rb

module Example
  module Routes
    class Routing < Base
      get '/?' do
        erb :home
      end
    end
  end
end

Why don't my error handlers work?

Thanks in advance.

Upvotes: 1

Views: 401

Answers (1)

matt
matt

Reputation: 79733

The use method is for adding middleware to an app, you can’t use it to compose an app like this.

In your example you actually have three different Sinatra applications, two of which are being run as middleware. When a Sinatra app is run as middleware then any request that matches one of its routes is handled by that app, otherwise the request is passed to the next component in the Rack stack. Error handlers will only apply if the request has been handled by the same app. The app that you have defined the error handlers in has no routes defined, so all requests will be passed on down the stack — the error handlers will never be used.

One way to organise a large app like this would be to simply use the same class and reopen it in the different files. This other question has an example that might be useful: Using Sinatra for larger projects via multiple files.

Upvotes: 4

Related Questions