Marr (Memereply Api Rescue Response)
Dynamically handle exceptions and render a structured JSON response to client applications.
Formerly (Memereply sad pepe)
Installation
Add this line to your application's Gemfile:
gem 'marr'
And then execute:
$ bundle
Or install it yourself as:
$ gem install marr
Example Response
{
"errors": {
"id": "6CA01AF9E592595F",
"code": "UnprocessableGroup",
"title": "Request can not be processed.",
"detail": "The Group can not be saved. Invalid or missing data.",
"meta": {
"object_errors": [
{
"pointer": "owner",
"detail": "Owner can't be blank"
},
{
"pointer": "name",
"detail": "Name can't be blank"
}
],
"trace_id": "6CA01AF9E592595F"
}
}
}
Usage
There is a method automatically created for each each class that inherits from Marr::ApiError. The method is preprended with 'raise'.
raise_unprocessable_group_error
You can also pass in options to your method for a more robust response:
raise_unprocessable_group_error(controller: self, subcode: :missing_data, object: @group)
Setup
Configure the gem. For the gem to recognize the descendant classes you have to provide the name space the errors are under.
Marr.configure do |config|
config.namespaces = ['Api::V1::Errors']
config.trace_id_length = 16
end
Create a new Error that inherits from the ApiError class. The class needs to be under the configured name space. NOTE: The message
method must be implemented.
module Api
module V1
module Errors
class UnprocessableGroup < ::Marr::ApiError
def message
"Request can not be processed."
end
def subcodes
super({
missing_data: 'The Group can not be saved. Invalid or missing data.',
})
end
end
end
end
end
Include the ErrorEngine module in your base api class
include ::Marr::Api::ErrorEngine
Next rescue all your api errors. This method could be in your base api class.
rescue_from 'Marr::ApiError' do |exception|
render exception.render, status: exception.status
end
If you are custom rendering using a gem like Jbuilder you can do something like this:
rescue_from 'Marr::ApiError' do |error|
@error = error
render @error.render, status: @error.status
end