LoginSignup
5
3

More than 5 years have passed since last update.

railsでエラー処理

Last updated at Posted at 2019-01-06

初めに

エラーハンドルの忘備録

rescue_from

application_controllerに

rescue_from Exception, with: :rescue_from_exception


def rescue_from_exception(e)
  @exception = e 
  render 'errors/500'
end 

みたいな感じで使えます。

あとはactive_recordのエラーハンドルで

rescue_from ActiveRecord::RecordNotFound, with: :record_not_found 

def record_not_found(e) 
  @exception = e
  render 'errors/record_not_found'
end 

とすればモデルなりデータがなかった時のエラーハンドルができる。

その他のエラーハンドルを実装する

例えばForbiddenというエラーを実装したい場合は

ActionControllerErrorでForbiddenを定義してあげればよいです。

class Forbidden < ActionController::ActionControllerError
end 

rescue_from Forbidden, with: :forbidden  

def forbidden(e)
  @exception = e 
  render 'errors/500'
end 

みたいな感じで使い

raise Forbidden,"テキスト"

で呼び出せます。

テキストに関してはあってもなくても大丈夫です。

次にrouting_errorの実装の仕方です。

routes.rbに

get '*wrong_routes' => 'routing_errors#index'
rails g controller routing_errors

として

routing_errors_controller.rbに

indexを定義する

def index 
  raise ActionController::RoutingError,"以下のurlにはアクセスできません => #{request.path.inspect}"
end 

あとはapplication_controller.rbに

rescue_from ActionController::RoutingError, with: :routing_error 

def routing_error(e)
  @exception = e 
  render 'errors/routing_error'
end 

と書いてerrorsフォルダの中にrouting_errorを書いたらおわり。

これに関してはrouting_errorsフォルダの下でもいいのかも知れないけどとりあえずまとめている。

とりあえずこんな感じだけどapplication_controllerの中身がでかくなるのでその場合はconcernに入れてすっきりさせればOK

5
3
2

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
3