Sha256: d2267ad4184527851889902cf772a1041979e90a3dae7f420d4b189f5c4cdc71

Contents?: true

Size: 1.15 KB

Versions: 3

Compression:

Stored size: 1.15 KB

Contents

module Rao
  module Api
    module ServiceController::ExceptionHandlingConcern
      extend ActiveSupport::Concern

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

        rescue_from ActiveRecord::RecordNotFound do |exception|
          handle_404(exception)
        end if Object.const_defined?(:ActiveRecord)
      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
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rao-api-service_controller-0.0.52.pre app/concerns/rao/api/service_controller/exception_handling_concern.rb
rao-api-service_controller-0.0.51.pre app/concerns/rao/api/service_controller/exception_handling_concern.rb
rao-api-service_controller-0.0.50.pre app/concerns/rao/api/service_controller/exception_handling_concern.rb