Handle invalid JSON payload in Rails 5+ API. Catch JSON parse error
When someone post invalid JSON payload to your Ruby on Rails URL endpoint then Rails crashes with 500 error. We could render nice message instead of the error. For instance if you have public API you may want to show reason of the error to explain to your API client why the request failed.
We can catch ActionDispatch::Http::Parameters::ParseError
in ApplicationController
. If you want to just catch this exception only for your API endpoints exposed by Rails then put the below code in proper API base controller.
Above tip works for Rails 5+. Hope you will find this useful. If you want to learn more how to faster test your API and Rails application then check out blog and website about knapsack_pro gem for CI parallelisation.