我試圖讓我的sinatra應用程序在服務器上發生錯誤(例如IOError或ArgumentError)時顯示自定義錯誤頁面。Sinatra - 錯誤處理
目前我正在使用AJAX將結果加載到某個#results
div,但如果在服務器出現錯誤時,我想要在新頁面上打開錯誤頁面。
當前,IOError顯示在服務器上,並且在控制檯中顯示錯誤(服務器響應的狀態爲500(內部服務器錯誤))。除此之外,沒有任何反應。
我認爲我必須玩Javascript(以及Sinatra :: Base類),但我已經花了整個昨天和今天早上沒有得到任何地方。
我會很感激任何幫助。我創建我的應用程序過於簡單的版本,我在下面顯示...
Sinatra_app.rb
require 'sinatra/base'
require9 'sinatra'
require 'slim'
# A helper module
module GVhelpers
def create_results(name)
# raise IOError, "There's a problem..."
return "<p>The Server Says 'Hey #{name}'</p>"
end
end
class GVapp < Sinatra::Base
helpers GVhelpers
set :root, File.dirname(__FILE__)
error do
@error = env['sinatra.error']
slim :"500", :locals => {:error => error}
end
get '/' do
slim :index
end
post '/form' do
name = params[:personName]
create_results(name)
end
end
GVapp.run!
index.slim(在視圖中的文件夾)
script src="/jquery.min.js"
script src="/Gvapp.js"
form#sayHey action="/form" method="post"
| Name:
input type="text" name="personName"
br
input type="submit"
#output
500.slim(在視圖文件夾中)
h1 Oops! Something went Wonky!
p Apologies, there was an error with your request:
strong request.env['sinatra.error'].message
p If the error persists, please contact the administrator.
Gvapp.js(公共文件夾)
$(document).ready(function() {
$('#sayHey').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/form',
data: $('#sayHey').serialize(),
success: function(response){
$('#output').html(response);
}
})
})
})
我也不得不添加一個錯誤塊到ajax來捕捉錯誤,但是非常感謝,真的有幫助... – 2014-10-07 16:01:39
'dump_errors'是另一個有用的,它將打印跟蹤到STDERR – 2017-08-18 21:06:58