Search code examples
rubysinatrahelper

How to handle errors in Sinatra from external file?


I'm trying to handle errors in a Sinatra App including a Helper Module. I tried doing it like this:

# application_controller.rb
require './application_helper'

class ApplicationController < Sinatra::Base
    helpers Sinatra::ApplicationHelper

end
# application_helper.rb

require 'sinatra/base'

module Sinatra
  module ApplicationHelper
    error StandardError do |e|
      handle_error 500, e
    end
  end

  helpers ApplicationHelper
end

But I cannot make it work, it is raising the error:

NoMethodError:
  undefined method `error' for Sinatra::ApplicationHelper:Module

How can I use error in an external module?


Solution

  • Rather than using the helpers method, you need to define a registered method on your helper module. In this method the parameter passed is your app, and you can use it to configure errors, for example:

    module Sinatra
      module ApplicationHelper
    
        def self.registered(app)
          app.error StandardError do |e|
            handle_error 500, e
          end
        end
      end
    
      register ApplicationHelper
    end
    

    Then in your app file you use register instead of helpers:

    class ApplicationController < Sinatra::Base
      register Sinatra::ApplicationHelper
    
    end
    

    You might want to add some helpers at the same time you register your extension, for example in this case you might want to include the handle_error method in the extension. To do that you can add another helper module inside your extension module, and call app.helpers to include it in registered.

    module Sinatra
      module ApplicationHelper
    
        module Helpers
          def handle_error(code, error)
            #... Helper code here.
          end
    
          # Other helpers if needed.
        end
    
        def self.registered(app)
          app.error StandardError do |e|
            handle_error 500, e
          end
    
          # Include helpers at registration.
          app.helpers Helpers
        end
      end
    
      register ApplicationHelper
    end