Skip to content

This gem allows you to catch any Ruby error risen in your app and format it automatically into nice JSON rseponse following jsonapi.org standards.

License

Notifications You must be signed in to change notification settings

driggl/jsonapi_errors_handler

Repository files navigation

Gem Version Codacy Badge Codacy Badge Run tests

JsonapiErrorsHandler

A convienient way to serialize errors in Jsonapi standard

Installation

Add this line to your application's Gemfile:

  gem 'jsonapi_errors_handler'

And then execute:

$ bundle

Or install it yourself as:

$ gem install jsonapi_errors_handler

Usage

In your controller:

  include JsonapiErrorsHandler
  rescue_from ::StandardError, with: lambda { |e| handle_error(e) }

From this point you'll have default html errors being serialized. JsonapiErrorsHandler offers 4 predefined errors:

If you rise any of errors above in any place of your application, client gets the nicely formatted error message instead of 500

Handling unexpected errors

If you want to handle all the errors in your API application to deliver nicely formatted JSON response about 500 instead crashing the server, add this when your application loads:

require 'jsonapi_errors_handler'

JsonapiErrorsHandler.configure do |config|
  config.handle_unexpected = true
end

Response Content-Type

If you want to change the response content type you can do it through the configuration setting content_type by default it is application/vnd.api+json

require 'jsonapi_errors_handler'

JsonapiErrorsHandler.configure do |config|
  config.content_type = 'application/json'
end

Custom errors mapping

If you want your custom errors being handled by default, just add them to the mapper

  include JsonapiErrorsHandler
  ErrorMapper.map_errors!({
      'ActiveRecord::RecordNotFound' => 'JsonapiErrorsHandler::Errors::NotFound'
  })
  rescue_from ::StandardError, with: lambda { |e| handle_error(e) }

Handling rails-specific validation errors

To handle validation errors from ActiveRecord or ActiveModel, you need to write custom error handler:

rescue_from ActiveRecord::RecordInvalid, with: lambda { |e| handle_validation_error(e) }
rescue_from ActiveModel::ValidationError, with: lambda { |e| handle_validation_error(e) }

def handle_validation_error(error)
  error_model = error.try(:model) || error.try(:record)
  messages = error_model.errors.messages
  mapped = JsonapiErrorsHandler::Errors::Invalid.new(errors: messages)
  render_error(mapped)
end

Custom error logging

When you'll include the jsonapi_errors_handler to your controller, all errors will be handled and delivered to the client in the nice, formatted way.

However, you'd probably like to have a way to log the risen error on your own to send notifications to developers that something unexpected happened.

To do so, just implement the log_error method in your controller, that accepts the risen error as an argument.

  def log_error(error)
    #do the fancy logging here
  end

Custom error responses

By default, we deliver hardcoded responses. You can check out the defined error classes for details

If you want to have custom error responses being delivered, just create your own Api::Errors that inherits from JsonapiErrorsHandler::StandardError

Localization example

If you want to localize your responses, just create a class:

  module Api::Errors
    class Forbidden < ::JsonapiErrorsHandler::Errors::StandardError
      def initialize(*)
        super(
          title: I18n.t('api.errors.forbidden.title'),
          status: 403,
          detail: I18n.t('api.errors.forbidden.detail'),
          source: { pointer: '/request/headers/authorization' }
        )
      end
    end
  end

Guides & tutorials

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/driggl/jsonapi_errors_handler.

How to contribute:

  1. Fork repository

  2. Install Rubocop - make sure you run it before commiting changes

  3. Commit changes

    • Keep commits small and atomic
    • Start commit message from keywords (Add/Remove/Change/Refactor/Move/Rename/Upgrade/Downgrade)
    • Keep commits imperative style
  4. Create Pull Request

License

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

About

This gem allows you to catch any Ruby error risen in your app and format it automatically into nice JSON rseponse following jsonapi.org standards.

Resources

License

Stars

Watchers

Forks

Packages

No packages published