简体   繁体   中英

ruby Grape Validation doesn't work

I write requires ,like this

params do
    requires :user_id, :type => Integer
    optional :page, :type => Integer, :default => 1
    optional :per_page, :type => Integer, :default => 20
end

and I have wrote rescue_from

rescue_from :all do |e|
  case e
  when Grape::Exceptions::ValidationErrors
    error!({ messages: e.full_messages }, 400)
  else
    Rails.logger.error "Api Error: #{e}"
    Rails.logger.error "#{e.backtrace.join("\n")}"
    error!({ messages: "errors" }, 500)
  end
end

but I cannot catch Grape::Exceptions::ValidationErrors without params[:user_id]

I don't know why your code doesn't work, but I can offer another working solution: rescue validation errors explicitly (above the rescue_from :all).

rescue_from Grape::Exceptions::ValidationErrors do |e|
  error!({ messages: e.full_messages }, 400)
end

rescue_from :all do |e|
  Rails.logger.error "Api Error: #{e}"
  Rails.logger.error "#{e.backtrace.join("\n")}"
  error!({ messages: "errors" }, 500)
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM