Error Response
is a json response gem to help you easily manage all your custom error statuses in your Rails application.
Add error_response
to your Rails application's Gemfile
.
gem 'error_response'
And then install the gem.
$ bundle install
Create your response config in config/error_response.yml
.
# config/error_response.yml
source:
local:
- your/local/file_1.yml
- your/local/file_2.yml
remote:
- https://your_remote_file_1.yml
- https://your_remote_file_2.yml
The error_response
gem looks up all yml
files and merge them into a hash.
You can also customize your config file path through configuration.
ErrorResponse.configure do |config|
config.yaml_config_path = 'your/local/config/file.yml'
end
Include helpers in your base application controller.
# in controller
class Api::ApplicationController < ActionController::Base
include ErrorResponse::Helper
...
end
The success response is used when the request is success. The response body is a hash with a data
key.
# in controller actions
data = { a: 1, b: 2 }
return success_response(data) if success?
response status: 200
response body:
{
"data": {
"a": 1,
"b": 2
}
}
The error response is used when the request is not valid. Therefore, you need to provide the error_key
defined in the config files.
# in controller actions
return error_response(:bad_request_1) if failed?
response status: 400
response body:
{
"error_code": 400001,
"error_message": "bad request 1",
"error_key": "bad_request_1"
}
You can also provide your custom error message and error data. If error data is a hash, it will be merged into the json response; If it is an array, it will be merged into the json response with an error_data
key.
# in controller actions
return error_response(:bad_request_1, 'no required data', { a: 1, b: 2 }) if failed?
response status: 400
response body:
{
"error_code": 400001,
"error_message": "bad request 1: no required data",
"error_key": "bad_request_1",
"a": 1,
"b": 2
}
If you do not want to handle the response in controllers, you can just raise an ErrorResponse::RequestError
exception. The gem will catach the exception in the base application controller and render an error_response.
# in any business logic file
raise ErrorResponse::RequestError.new(:bad_request_1)
See all available error_code & error_message
ErrorResponse.all
Return to hash only
ErrorResponse.to_hash(:bad_request_1)
gives you
response status: 400
response body:
{
"error_code": 400001,
"error_message": "bad request 1",
"error_key": "bad_request_1"
}
The gem is available as open source under the terms of the MIT License.