2013-02-16 32 views
3

我希望有人能夠幫助解決這個問題。當引發異常時Rails渲染html而不是json

我有一個Web服務應用程序,我正在寫軌道。我使用的服務爲RocketPants,授權使用Authority

我遇到了異常處理問題,其中「現在允許」異常(Authority :: SecurityViolation)的權限呈現爲HTML,而不是JSON。

我已經在this gistthis issue中記錄了這個故事。

我可以通過在我的ApiController中產生一個異常來複制像raise "blah",並且我得到一個html錯誤頁面。我試過使用rescue_from,就像this question一樣,結果不一樣。

我不知道從哪裏來。任何人都知道導致這種情況的Rails異常處理堆棧中的任何內容?我會很感激任何幫助。

回答

2

你是否在你的ApiController類中試過這個?

rescue_from StandardError, with: :render_unknown_error 


def render_unknown_error(error) 
    render(json: error.inspect, status: 500) 
end 
+2

[爲什麼你不應該拯救異常的紅寶石(http://daniel.fone.net.nz/blog/2013/05/28/why-you-should-never-rescue-exception-in -ruby /) 本文建議您應該捕獲StandardError或更具體的東西。 – ChristopherJ 2014-09-02 01:18:50