Exception: BetterService::Errors::Runtime::ValidationError

Inherits:
RuntimeError show all
Defined in:
lib/better_service/errors/runtime/validation_error.rb

Overview

Raised when parameter validation fails

This error is raised during service initialization when Dry::Schema validation fails. The validation errors are available in the context.

Examples:

Validation failure

class MyService < BetterService::Services::Base
  schema do
    required(:email).filled(:string)
    required(:age).filled(:integer, gt?: 18)
  end
end

MyService.new(user, params: { email: "", age: 15 }).call
# => raises ValidationError with context:
# {
#   service: "MyService",
#   validation_errors: {
#     email: ["must be filled"],
#     age: ["must be greater than 18"]
#   }
# }

Handling validation errors

begin
  MyService.new(user, params: invalid_params).call
rescue BetterService::Errors::Runtime::ValidationError => e
  render json: {
    error: e.message,
    validation_errors: e.context[:validation_errors]
  }, status: :unprocessable_entity
end

Instance Attribute Summary

Attributes inherited from BetterServiceError

#code, #context, #original_error, #timestamp

Instance Method Summary collapse

Methods inherited from BetterServiceError

#backtrace, #detailed_message, #inspect, #to_h

Constructor Details

#initialize(message = "Validation failed", code: :validation_failed, context: {}, original_error: nil) ⇒ ValidationError

Returns a new instance of ValidationError.



39
40
41
# File 'lib/better_service/errors/runtime/validation_error.rb', line 39

def initialize(message = "Validation failed", code: :validation_failed, context: {}, original_error: nil)
  super(message, code: code, context: context, original_error: original_error)
end