Skip to content

Instantly share code, notes, and snippets.

@dhamkur
Forked from ArturT/api_controller.rb
Created May 8, 2023 19:18
Show Gist options
  • Save dhamkur/62eaeb3981ee0e140549db1e8acd0422 to your computer and use it in GitHub Desktop.
Save dhamkur/62eaeb3981ee0e140549db1e8acd0422 to your computer and use it in GitHub Desktop.
How to rescue ActionDispatch::Http::MimeNegotiation::InvalidType in API controller for Rails 6.1+ and render nice JSON error. Learn more how you could run RSpec/Minitest tests faster in Rails app https://docs.knapsackpro.com/2020/how-to-speed-up-ruby-and-javascript-tests-with-ci-parallelisation
# This is example how to rescue from exception ActionDispatch::Http::MimeNegotiation::InvalidType
# and show nice JSON error in your API
module API
class BaseController < ActionController::API
def process_action(*args)
super
rescue ActionDispatch::Http::MimeNegotiation::InvalidType => exception
# set valid Content-Type to be able to call render method below
request.headers['Content-Type'] = 'application/json'
render status: 400, json: { errors: [exception.message] }
end
end
end
# This if full example for your API in Rails 6.1+ that will render errors as JSON instead of ugly HTML error page
module API
class BaseController < ActionController::API
def process_action(*args)
super
rescue ActionDispatch::Http::Parameters::ParseError => exception
# https://github.com/rails/rails/issues/34244#issuecomment-433365579
render status: 400, json: { errors: [exception.message] }
rescue ActionDispatch::Http::MimeNegotiation::InvalidType => exception
# set valid Content-Type to be able to call render method below
request.headers['Content-Type'] = 'application/json'
render status: 400, json: { errors: [exception.message] }
end
# This will work for Rails > 5.2.2
# https://github.com/rails/rails/pull/34341#issuecomment-434727301
rescue_from ActionDispatch::Http::Parameters::ParseError do |exception|
render status: 400, json: { errors: [exception.cause.message] }
end
end
end
# This if full example for your API in Rails < 6.1 that will render errors as JSON instead of ugly HTML error page
module API
class BaseController < ActionController::API
def process_action(*args)
super
rescue ActionDispatch::Http::Parameters::ParseError => exception
# https://github.com/rails/rails/issues/34244#issuecomment-433365579
render status: 400, json: { errors: [exception.message] }
rescue Mime::Type::InvalidMimeType => exception
render status: 400, json: { errors: [exception.message] }
end
# This will work for Rails > 5.2.2
# https://github.com/rails/rails/pull/34341#issuecomment-434727301
rescue_from ActionDispatch::Http::Parameters::ParseError do |exception|
render status: 400, json: { errors: [exception.cause.message] }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment