【问题标题】:sinatra redirect on errorsinatra 错误重定向
【发布时间】:2012-11-17 08:38:05
【问题描述】:

我在 Sinatra 模块化应用程序中出现重定向错误的问题。 我在 Heroku 上部署,当出现错误时,应用程序会死掉。

我希望它能捕捉到这个错误,重定向到错误页面并正常运行。

我在我的基类中设置如下:

set :raise_errors, false

error do
    redirect to('/')
end

但是当我在路由块内出现raise 错误时,它只会转到标准的 Sinatra 错误页面。

我需要做些什么来捕获我的错误并重定向?

【问题讨论】:

    标签: ruby heroku sinatra


    【解决方案1】:

    你还需要

    set :show_exceptions, false
    

    这是一个简单的演示

    require "sinatra"
    
    class App < Sinatra::Base
    
        set :raise_errors, false
        set :show_exceptions, false
    
        get '/' do
            return 'Hello, World!'
        end
    
        get '/error' do
            return 'You tried to divide by zero!'
        end
    
        get '/not-found' do
            return 'There is nothing there'
        end
    
        get '/raise500' do
            raise 500
        end
    
        get '/divide-by-zero' do
            x = 5/0
        end
    
        error do
            redirect to('/')
        end
    
        error 404 do
            redirect to('/not-found')
        end
    
        error ZeroDivisionError do
            redirect to('/error')
        end
    
    end
    

    如果没有 :show_exceptions 设置 /raise500/divide-by-zero 将返回通用 Sinatra 错误页面,但它们会按照您的预期重定向。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-04
      • 2023-03-27
      • 2017-12-22
      • 2010-11-18
      相关资源
      最近更新 更多