Last active
November 5, 2024 19:42
-
-
Save Hasstrup/d72589560633db12c64c8e0d1c840072 to your computer and use it in GitHub Desktop.
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 | |
| # The ErrorHandling module provides mechanisms for managing errors | |
| # within service classes. It includes methods for safely executing | |
| # blocks of code and handling known error classes. | |
| module ErrorHandling | |
| module Core | |
| # A list of error classes that can be rescued during safe execution. | |
| ERROR_CLASSES = [ | |
| ActiveRecord::RecordNotFound, | |
| ActiveRecord::RecordInvalid, | |
| ActiveModel::UnknownAttributeError, | |
| ActiveRecord::StatementInvalid, | |
| BaseService::InvalidInputError, | |
| BaseService::ServiceError | |
| ].freeze | |
| # Safely executes a block of code, running checks if needed. | |
| # | |
| # @yield [void] The block of code to execute. | |
| # @return [Context] The context after execution. | |
| def safely_execute(&block) | |
| run_checks! if should_run_checks? | |
| block.call | |
| context | |
| rescue *ERROR_CLASSES => e | |
| fail!(error: e) | |
| end | |
| # Runs input validation checks. Must be implemented by the including class. | |
| # | |
| # @raise [NotImplementedError] When not implemented in a subclass. | |
| def run_checks! | |
| raise BaseService::InvalidInputError, input.errors.flat_map(&:message) unless input.valid? | |
| end | |
| end | |
| module Validatable | |
| module ClassMethods | |
| # Indicates that checks should be performed on input validation. | |
| # | |
| # @return [void] | |
| def performs_checks | |
| @should_run_checks = true | |
| end | |
| attr_reader :should_run_checks | |
| end | |
| # Checks if validation checks should be performed. | |
| # | |
| # @return [Boolean] True if checks should be performed; otherwise, false. | |
| def should_run_checks? | |
| self.class.should_run_checks | |
| end | |
| def self.included(base) | |
| base.include(Core) | |
| base.extend(ClassMethods) | |
| end | |
| def raise_error!(message) | |
| raise BaseService::ServiceError, message | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment