5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Rails】RoutingError時の処理を書く

Last updated at Posted at 2016-06-08

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が呼ばれちゃうみたいです。

5
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?