【问题标题】:Error handlers don't run in modular Sinatra app错误处理程序不在模块化 Sinatra 应用程序中运行
【发布时间】:2014-09-25 16:28:09
【问题描述】:

我有一个使用模块化样式的 Sinatra 应用程序。除了没有被调用的错误处理程序块之外,一切正常。以下是相关代码:

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

为什么我的错误处理程序不起作用?

提前致谢。

【问题讨论】:

    标签: ruby sinatra


    【解决方案1】:

    use method is for adding middleware to an app,你不能用它来编写这样的应用程序。

    在您的示例中,您实际上有 三个 不同的 Sinatra 应用程序,其中两个作为中间件运行。当 Sinatra 应用程序作为中间件运行时,任何与其中一条路由匹配的请求都由该应用程序处理,否则该请求将传递给 Rack 堆栈中的下一个组件。错误处理程序仅适用于请求已由同一应用程序处理的情况。您在其中定义了错误处理程序的应用程序定义了 no 个路由,因此所有请求都将沿堆栈向下传递——永远不会使用错误处理程序。

    像这样组织大型应用程序的一种方法是简单地使用相同的类并在不同的文件中重新打开它。另一个问题有一个可能有用的示例:Using Sinatra for larger projects via multiple files

    【讨论】:

    • 谢谢,这是有道理的。我实际上是在遵循这里概述的架构:blog.sourcing.io/structuring-sinatra
    • 但它不应该因为Routing 继承Base 的错误处理而工作吗?因为Base 没有任何溃败,所以它没有处理请求,因此将它传递给RoutingRouting 通过继承进行错误处理,所以它应该可以工作,对吧?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    • 2014-05-23
    相关资源
    最近更新 更多