Created
September 30, 2021 21:03
-
-
Save 1997roylee/59fd37b5dd5f62d2567c82af29d07f2e to your computer and use it in GitHub Desktop.
BaseError
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
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
Example