-
Notifications
You must be signed in to change notification settings - Fork 0
Basic usage
Łukasz Pająk edited this page Aug 3, 2021
·
1 revision
First, run the json_errors:install
generator:
> rails g json_errors:install
create config/initializers/json_errors.rb
It creates the initializer file with config. Check out the file and uncomment what you need.
Then include JsonErrors::Rescuer
to your JSON API controller and start raising errors.
class UsersController < ApplicationController
include JsonErrors::Rescuer
def create
user = User.create!(params.require(:name))
head :created
end
end
Be sure to use error throwing methods everywhere, like create!
, save!
, find_by!
, etc. The gem will rescue from any exception and respond with a properly formatted JSON body with a custom error code.
No need for rescue_from
or rendering the JSON error body. Every error is rescued, logged, formatted and rendered. The client application will receive a JSON body like this:
{
"code":1010,
"message":"The parameter 'name' is missing or value is empty"
}