這個應該是有點 lag 了,不過以前沒用到也就一直沒有注意這個東西。XD
在寫網頁的時候,我們常常會遇到要處理發生 error 的狀況。不管是你想寫封信煩死你自己或是顯示和藹可親的錯誤畫面,或是像我這個 case:我寫的是 JSON Web Service Server,所以我希望錯誤訊息也可以包在 JSON 傳回去。程式碼很簡單,就像:
1 2 3 4 5 6 7 8 | rescue_from Exception do |ex| if ex.class == ActionController::RoutingError json_response('err', '404 Not Found') else json_response('err', '500 Internal Server Error' + (ENV['RAILS_ENV'] == 'development' ? " (#{ex.message})" : '')) end end |
(當然這個 json_response 是我自己寫的函式,你可以換掉。)
簡單的說,你只需要寫 rescue_from [Exception 類型] do |ex| … end 這樣,在 clousure 裡頭處理你的錯誤就可以了。如果你把這段 code 放在 ApplicationController 就會變成 catch-all 的處理函式(因為所有 controller 都繼承 ApplicationController),如果只想處理特定的 controller 則放在該 controller 底下即可。

留言 Comments