Sha256: db6abe5a0842447c0a800fab5afbcfdb8fdeb918fdb7776dae87c23a0b89f60a

Contents?: true

Size: 1.03 KB

Versions: 7

Compression:

Stored size: 1.03 KB

Contents

module ApiControllerConcerns
  module ExceptionHandling
    extend ActiveSupport::Concern

    included do
      rescue_from Exception do |exception|
        handle_exception(exception)
      end

      rescue_from ActiveRecord::RecordNotFound do |exception|
        handle_404(exception)
      end
    end

    private

    def handle_404(exception = nil)
      respond_to do |format|
        format.json { render json: { error: (exception.try(:message) || 'Not found') }, status: 404 }
      end
    end

    def handle_exception(exception)
      if Rails.env.development? || Rails.env.test?
        error = { message: exception.message }

        error[:application_trace] = Rails.backtrace_cleaner.clean(exception.backtrace)
        error[:full_trace] = exception.backtrace

        respond_to do |format|
          format.json { render json: error, status: 500 }
        end
      else
        respond_to do |format|
          format.json { render json: { error: 'Internal server error.' }, status: 500 }
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
rails-add_ons-3.0.0.pre1 app/concerns/api_controller_concerns/exception_handling.rb
rails-add_ons-2.2.1 app/concerns/api_controller_concerns/exception_handling.rb
rails-add_ons-2.2.0 app/concerns/api_controller_concerns/exception_handling.rb
rails-add_ons-2.1.1 app/concerns/api_controller_concerns/exception_handling.rb
rails-add_ons-2.1.0 app/concerns/api_controller_concerns/exception_handling.rb
rails-add_ons-2.0.2 app/concerns/api_controller_concerns/exception_handling.rb
rails-add_ons-2.0.1 app/concerns/api_controller_concerns/exception_handling.rb