Skip to content

Instantly share code, notes, and snippets.

@1997roylee
Created September 30, 2021 21:03
Show Gist options
  • Save 1997roylee/59fd37b5dd5f62d2567c82af29d07f2e to your computer and use it in GitHub Desktop.
Save 1997roylee/59fd37b5dd5f62d2567c82af29d07f2e to your computer and use it in GitHub Desktop.
BaseError
# frozen_string_literal: true
module Errors
module BaseError
extend ActiveSupport::Concern
included do
class_attribute :errors, instance_accessor: false
self.errors = Hash.new({ status: nil, code: nil, message: nil })
end
module ClassMethods
attr_reader :errors
def status(status)
self.errors = errors.merge({ status: status })
end
def code(code)
self.errors = errors.merge({ code: "ERROR_#{code.upcase}" })
end
def message(message)
self.errors = errors.merge({ errors: message })
end
end
end
end
@1997roylee
Copy link
Author

Example

module Errors
    module AuthError
        class NotReadyForSendConfirmation
            include BaseError
            status 400
            code 'not_ready_for_send_confirmation'
            message 'Please wait 1 minute to send the confirmation email'
        end
    end
end

@1997roylee
Copy link
Author

Rendering

    def render_errors!(exception, errors = nil)
        errors = if errors.nil?
                     exception.errors
                 else
                     exception.message(errors)
                 end

        raise 'Unknown Error' unless errors.present?

        render json: errors.merge({ success: false }),
               status: errors[:status]
    end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment