2014-10-07 82 views
1

我試圖讓我的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); 
     } 
    }) 

    }) 
}) 

回答

4

西納特拉在development環境默認運行並顯示其調試錯誤頁面,而不是當燕子例外。因此,要觸發自定義錯誤處理程序,您必須在除development(可能爲production)之外的Rack環境中運行應用程序,或者最好告訴Sinatra 而不是development模式下使用其默認錯誤處理程序。

考慮下面的,獨立的西納特拉應用舉例:如果您運行使用默認development環境這樣該應用

require "sinatra" 

#disable :show_exceptions 

get "/" do 
    raise RuntimeError.new("boom") 
end 

error RuntimeError do 
    "A RuntimeError occured" 
end 

$ ruby foo.rb 

然後你會得到Sinatra的默認錯誤頁面。如果您在示例中取消註釋disable行,則將觸發error處理程序,而不是顯示包含「發生A RuntimeError」的頁面。或者,您可以像解釋的那樣在除development之外的環境中運行應用程序,因爲只有該應用程序預先設置了show_exception設置。你可以做,通過設置RACK_ENV環境變量:

$ RACK_ENV=production ruby foo.rb 

對於開發目的,設置RACK_ENVproduction當然不是正確的方法。改爲使用disable :show_exceptions。您可以使用configure塊作爲outlined in the Sinatra README以有條件地禁用development環境的設置。

configure :development do 
    disable :show_exceptions 
end 

該行爲記錄在Sinatra’s documentation on configuration以及其他一些有用的設置中。

+0

我也不得不添加一個錯誤塊到ajax來捕捉錯誤,但是非常感謝,真的有幫助... – 2014-10-07 16:01:39

+0

'dump_errors'是另一個有用的,它將打印跟蹤到STDERR – 2017-08-18 21:06:58