我在 Sinatra 模块化应用程序中遇到错误重定向问题。 我正在 Heroku 上进行部署,当出现错误时,应用程序会停止运行。
我希望它能捕捉到这个错误,重定向到错误页面并正常运行。
我在我的基类中设置如下:
set :raise_errors, false
和
error do
redirect to('/')
end
但是当我从路由 block 中引发
错误时,它只会转到标准的 Sinatra 错误页面。
我需要做什么来捕获我的错误并重定向?
请您参考如下方法:
你还需要
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 错误页面,但是它们重定向为你会期望。