LoginSignup
8
9

More than 5 years have passed since last update.

grapeバリデーションのエラーハンドリングの仕方

Posted at

grapeでは、以下のように、パラメーターとして受け取る値にtypeを指定して、
あらかじめバリデーションをかけることができる。

params :sample_params do
   optional :locale, type: String, desc: 'locale'
   requires :auth_token, type: String, desc: 'auth_token'
   requires :age, type: Integer, desc: 'age'
   requires :data, type: Array[String], desc: 'data'
end

しかし、このバリデーションには意外な欠点があって、
例えば値が空な時に発火するよう自作した俺俺エラーがあったとしても、
それがraiseする前にgrape validationのエラーがraiseしてしまう。
その為、grapeが発火させるエラーをいい感じで整形してレスポンスを返したい。

そんな時は、resque_fromを使ってあげよう。

module API
  class ApiBase < Grape::API

    rescue_from Grape::Exceptions::ValidationErrors do |e|
      case JSON.parse(e.to_json)[0]["params"][0]
          when "auth_token"
            error!({
                  errors: [
                    {
                      message: I18n.t('errors.messages.invalid_auth_token'),
                      code: ErrorCodes::INVALID_TOKEN
                    }
                  ]
                },400)
          when "serial_number"
            error!({
                  errors: [
                    {
                      message: I18n.t('errors.messages.invalid_serial_number'),
                      code: ErrorCodes::SERIAL_PARAMS
                    }
                  ]
                },400)
      end
    end

    # 中略

   mount V2::Hoge
  end
end

エラーフォーマッターをうまく使えば解決できるのかもしれ無いけれど、
上記の方法で簡単に実装できたので良しとした。

8
9
1

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
8
9