【问题标题】:How to handle errors in Sinatra from external file?如何处理来自外部文件的 Sinatra 错误?
【发布时间】:2021-10-29 12:59:33
【问题描述】:

我正在尝试处理 Sinatra 应用程序中的错误,包括帮助程序模块。我试着这样做:

# 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

但我无法让它工作,它引发了错误:

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

如何在外部模块中使用error

【问题讨论】:

    标签: ruby sinatra helper


    【解决方案1】:

    您需要在帮助模块上使用define a registered method,而不是使用helpers 方法。在这个方法中传递的参数是你的应用,你可以使用它来配置错误,例如:

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

    然后在您的应用文件中使用register 而不是helpers

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

    您可能希望在注册扩展程序的同时添加一些帮助程序,例如,在这种情况下,您可能希望在扩展程序中包含 handle_error 方法。为此,您可以在扩展模块中添加另一个帮助模块,然后调用 app.helpers 将其包含在 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多