Exception: BetterService::Errors::Runtime::AuthorizationError

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

Overview

Raised when user is not authorized to perform the action

This error is raised when the authorize_with block returns false. Authorization checks happen before the service execution begins.

Examples:

Authorization failure

class Post::DestroyService < BetterService::Services::DestroyService
  model_class Post

  schema do
    required(:id).filled(:integer)
  end

  authorize_with do
    resource.user_id == user.id  # Only owner can delete
  end
end

# User tries to delete someone else's post
Post::DestroyService.new(current_user, params: { id: other_users_post_id }).call
# => raises AuthorizationError

Handling authorization errors

begin
  MyService.new(user, params: params).call
rescue BetterService::Errors::Runtime::AuthorizationError => e
  render json: { error: e.message }, status: :forbidden
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 = "Not authorized", code: :unauthorized, context: {}, original_error: nil) ⇒ AuthorizationError

Returns a new instance of AuthorizationError.



35
36
37
# File 'lib/better_service/errors/runtime/authorization_error.rb', line 35

def initialize(message = "Not authorized", code: :unauthorized, context: {}, original_error: nil)
  super(message, code: code, context: context, original_error: original_error)
end