【问题标题】:override not_found sinatra application覆盖 not_found sinatra 应用程序
【发布时间】:2015-05-01 10:07:33
【问题描述】:
sinatra (= 1.4.5)

我想为特定路线呈现自定义 404 消息,在本例中为文本“未找到”

class App < Sinatra::Application 

  not_found do
    'You suck'
  end

  get '/404page' do
    halt 404, 'Not found'
  end 
end

我发现无论我做什么,只要响应状态设置为 404,就会调用来自 not_found block 的文本,而我真正想要的只是来自停止的文本。

可能与Override Sinatra default NotFound error page 重复,但我找不到解决方案。

【问题讨论】:

    标签: ruby sinatra


    【解决方案1】:

    在未找到特定路由时,覆盖 error Sinatra::NotFound 似乎是处理 404 的更好选择。

    error Sinatra::NotFound do
      'You suck'
    end
    
    get '/404page' do
      halt 404, 'Not found'
    end
    

    【讨论】:

    • 这对我有用,因为我有另一个 error 404 do 处理程序,所以我可以区分我自己的 404 错误和 API 端点未命中 (Sinatra::NotFound)
    【解决方案2】:

    您可以将正文传递给 not_found,因此您的 get 请求看起来像这样。

    get '/404page' do
      not_found('Not found')
    end
    

    这将通过 not_found 方法调用halt 404, 'Not found'

    这通常是您需要的;如果这不适合您的需求,那么您需要考虑覆盖 Sinatra route_missing 方法,我在下面提供了该方法。

    # No matching route was found or all routes passed. The default
    # implementation is to forward the request downstream when running
    # as middleware (@app is non-nil); when no downstream app is set, raise
    # a NotFound exception. Subclasses can override this method to perform
    # custom route miss logic.
    def route_missing
      if @app
        forward
      else
        raise NotFound
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2012-08-29
      • 2011-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多