LoginSignup
10
5

More than 5 years have passed since last update.

Rails+Grapeでエラーハンドリング

Last updated at Posted at 2016-07-15

やりたいこと

  • 普通にRails+Grapeを使っていると、ハンドルされない例外が発生したときRailsのエラーページが返ってしまうが、独自のJSONを返すようにしたい。HTTPステータスは500(Internal Server Error)にしたい。
  • Grapeのパラメータチェックにひっかかった場合はHTTPステータスは400(Bad Request)にしたい。

環境

  • Rails 4.2.6
  • Grape 0.16.2

手順

自分のAPIクラスに記述:

class MyAPI < Grape::API
  # rescue_fromは書いた順番にマッチングされる

  # Grapeの例外の場合は400を返す
  rescue_from Grape::Exceptions::Base do |e|
    error!(e.message, 400)
  end

  # それ以外は500
  rescue_from :all do |e|
    error!({error: e.message, backtrace: e.backtrace[0]}, 500)
  end
end

ぐぐるとerror!でなくerror_responseというメソッドを使っているページがあるが、error_responseは非推奨らしい:

grape-0.16.2/lib/grape/middleware/error.rb
      # TODO: This method is deprecated. Refactor out.
      def error_response(error = {})
10
5
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
10
5