PlayGround Article grapeバリデーションのエラーハンドリングの仕方 gamerinshaft 2015年12月22日 Created with Sketch. 0 Created with Sketch. 328 grapeでは、以下のように、パラメーターとして受け取る値に`type`を指定して、 あらかじめバリデーションをかけることができる。 ```rb 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`を使ってあげよう。 ```rb 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 ``` エラーフォーマッターをうまく使えば解決できるのかもしれ無いけれど、 上記の方法で簡単に実装できたので良しとした。