Sha256: f68846b804693ef422ea5714ec6e0f1e3eb629b26622c29bdcbade772de167d5

Contents?: true

Size: 1.39 KB

Versions: 3

Compression:

Stored size: 1.39 KB

Contents

require 'net/http/status'
require 'active_support/concern'

module JSONAPI
  # Helpers to handle some error responses
  #
  # Most of the exceptions are handled in Rails by [ActionDispatch] middleware
  # See: https://api.rubyonrails.org/classes/ActionDispatch/ExceptionWrapper.html
  module Errors
    extend ActiveSupport::Concern

    included do
      rescue_from StandardError do |exception|
        error = { status: '500', title: Net::HTTP::STATUS_CODES[500] }
        render jsonapi_errors: [error], status: :internal_server_error
      end

      [
        ActiveRecord::RecordNotFound
      ].each do |exception_class|
        rescue_from exception_class do |exception|
          error = { status: '404', title: Net::HTTP::STATUS_CODES[404] }
          render jsonapi_errors: [error], status: :not_found
        end
      end

      [
        ActionController::ParameterMissing
      ].each do |exception_class|
        rescue_from exception_class do |exception|
          source = { pointer: '' }

          if !%w{data attributes relationships}.include?(exception.param.to_s)
            source[:pointer] = "/data/attributes/#{exception.param}"
          end

          error = {
            status: '422',
            title: Net::HTTP::STATUS_CODES[422],
            source: source
          }

          render jsonapi_errors: [error], status: :unprocessable_entity
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
jsonapi.rb-1.1.3 lib/jsonapi/errors.rb
jsonapi.rb-1.1.2 lib/jsonapi/errors.rb
jsonapi.rb-1.1.1 lib/jsonapi/errors.rb