Module: ZeroRuby::ErrorFormatter

Defined in:
lib/zero_ruby/error_formatter.rb

Overview

Formats Dry::Types and Dry::Struct errors into user-friendly messages using dry-schema’s built-in message templates.

Constant Summary collapse

MESSAGES =

Get the dry-schema messages backend for English

Dry::Schema::Messages::YAML.build

Class Method Summary collapse

Class Method Details

.format_coercion_error(error) ⇒ String

Format a Dry::Types::CoercionError into user-friendly message

Parameters:

  • error (Dry::Types::CoercionError)

    The coercion error

Returns:

  • (String)

    Formatted error message



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/zero_ruby/error_formatter.rb', line 40

def format_coercion_error(error)
  message = error.message
  input = error.respond_to?(:input) ? error.input : nil

  type = extract_type_name(message)
  if input
    value_str = format_value(input)
    "#{value_str} is not a valid #{type}"
  else
    lookup_message(:type?, type) || "must be a #{type}"
  end
end

.format_constraint_error(error) ⇒ String

Format a Dry::Types::ConstraintError into user-friendly message

Parameters:

  • error (Dry::Types::ConstraintError)

    The constraint error

Returns:

  • (String)

    Formatted error message



56
57
58
# File 'lib/zero_ruby/error_formatter.rb', line 56

def format_constraint_error(error)
  format_constraint_message(error.message)
end

.format_struct_error(error) ⇒ Array<String>

Format a Dry::Struct::Error into user-friendly messages

Parameters:

  • error (Dry::Struct::Error)

    The struct error

Returns:

  • (Array<String>)

    Formatted error messages



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/zero_ruby/error_formatter.rb', line 16

def format_struct_error(error)
  message = error.message

  if message.include?("is missing")
    match = message.match(/:(\w+) is missing/)
    field = match ? match[1] : "field"
    ["#{field} is required"]
  elsif message.include?("has invalid type")
    # Matches both ":title has invalid type" and "has invalid type for :title"
    match = message.match(/:(\w+) has invalid type/) ||
      message.match(/has invalid type for :(\w+)/)
    field = match ? match[1] : "field"
    ["#{field}: invalid type"]
  elsif message.include?("violates constraints")
    # Extract constraint info and format it
    [format_constraint_message(message)]
  else
    [message]
  end
end