JSONError

Code Climate

Installation

Add this line to your application's Gemfile:

gem 'json_error', github: 'buszu/json_error'

And then execute:

$ bundle

Usage

Defining JSONErrors

module Errors
  class ResourceNotFound < JSONError.base
    def initialize(options = {})
      # Add required :key option
      options.merge!(key: :resource_not_found)
      super(options)
    end
  end

  class OtherError < JSONError.base
    # Slice response JSON properties
    def self.properties
      super - %i(href description)
    end

    options.merge!(key: :other_error)
    super(options)
  end
end

Defining JSONError Properties

Add entries below to your locale.

en:
  errors:
    resource_not_found:
      status: 404
      message: 'Resource %{name} (%{id}) was not found.'
      description: 'Blah blah blah.'
      href: 'https://developers.api.pl/doc/errors/resource_not_found'

Rendering JSONError

Rails

# app/controllers/batmans_controller.rb
class BatmansController < ApplicationController
  def index
    error = Errors::ResourceNotFound.new(name: :Batman, id: 2)
    render json: error, status: error.status
  end
end

# or

class BatmansController < ApplicationController
  def index
    raise Errors::ResourceNotFound, name: :Batman, id: 2
  rescue JSONError.base => e
    render json: e, status: e.status
  end
end

Sinatra

# Remember to load dependencies

class Application < Sinatra::Base
  before { content_type :json }

  get '/batmans' do
    error = Errors::ResourceNotFound.new(name: :Batman, id: 2)
    halt error.status, json(error)
  end
end

Responses

For ResourceNotFound

{
  "status": 404,
  "key": "resource_not_found",
  "message": "Resource Batman (2) was not found.",
  "description": "Blah blah blah.",
  "href": "https://developers.api.pl/doc/errors/resource_not_found"
}

For OtherError

{
  "status": 500,
  "key": "other_error",
  "message": null
}

Using Contexts

You can specify different contexts for the same error key.

# In locale

en:
  errors:
    resource_not_found:
      status: 404
      message: 'Resource %{name} (%{id}) was not found.'
      description: 'Blah blah blah.'
      href: 'https://developers.api.pl/doc/errors/resource_not_found'
    batmans:
      resource_not_found:
        status: 404
        message: 'Resource Batman (%{id}) was not found.'
        description: "Cuz I'm Batman"
# In constructor

Errors::ResourceNotFound.new(context: 'batmans', id: 2)
// And then response will look like below

{
  "status": 404,
  "key": "resource_not_found",
  "message": "Resource Batman (2) was not found.",
  "description": "Cuz I'm Batman",
  "href": null
}

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/json_error.

License

The gem is available as open source under the terms of the MIT License.