routes.rb
routes.rbにマッチしないルートが呼ばれた時のアクションを設定します
match '*unmatched_route', :to => 'application#raise_not_found!', :via => :all
ApplicationController.rb
ApplicationControllerのメソッドにアクションとエラー時のハンドラーを実装します。
#called by last route matching unmatched routes. Raises RoutingError which will be rescued from in the same way as other exceptions.
def raise_not_found!
raise ActionController::RoutingError.new("No route matches #{params[:unmatched_route]}")
end
def error_404(exception)
// 処理を書く
end
補足
get '*unmatched_route', to: 'application#render_404', format: false
routes.rbで登録するアクションに直接ハンドラーを指定しても大丈夫みたいです。
どっちが正しいやりかたなのか誰か教えてください。
ちなみに
rescue_from Exception, :with => :error_500
rescue_from ActionController::RoutingError, with: :render_404
ちなみにこのようにExceptinのエラーも捕捉してたりする場合は、その後ろにrescue_from ActionController::RoutingError, with: :render_404
書かないとRoutingError時もerror_500が呼ばれちゃうみたいです。