IdentifierCannotBeEmptyException

Overview

IdentifierCannotBeEmptyException is a custom exception class in the Midnite81\Guardian package. This exception is thrown when an attempt is made to set an empty identifier in the Guardian system.

Class Details

  • Namespace: Midnite81\Guardian\Exceptions

  • Extends: Exception

Purpose

The primary purpose of this exception is to ensure that valid, non-empty identifiers are always used within the Guardian system. Identifiers are crucial for distinguishing between different rate-limited resources or actions. Guardian does not allow for empty identifiers and will throw this exception.

Usage

This exception is typically thrown by the Guardian system when setting or updating an identifier. It's most commonly encountered in the Guardian class constructor or when using the setIdentifier method.

Example of where this exception might be thrown:

use Midnite81\Guardian\Guardian;
use Midnite81\Guardian\Exceptions\IdentifierCannotBeEmptyException;

try {
    $guardian = new Guardian('', $cache);  // This will throw IdentifierCannotBeEmptyException
} catch (IdentifierCannotBeEmptyException $e) {
    echo "Error: " . $e->getMessage();
}

Best Practices

  1. Always provide a non-empty string as an identifier when creating a new Guardian instance or setting an identifier.

  2. Catch this exception when there's a possibility of receiving an empty identifier from user input or external sources.

  3. Provide meaningful identifiers that represent the resource or action being rate-limited.

Error Message

The default error message for this exception is:

Identifier cannot be empty

Handling the Exception

When catching this exception, you should handle it by either:

  1. Providing a default identifier

  2. Logging the error

  3. Notifying the user or system administrator about the invalid input

Example:

use Midnite81\Guardian\Guardian;
use Midnite81\Guardian\Exceptions\IdentifierCannotBeEmptyException;

function createGuardian($identifier, $cache) {
    try {
        return new Guardian($identifier, $cache);
    } catch (IdentifierCannotBeEmptyException $e) {
        // Log the error
        error_log("Attempted to create Guardian with empty identifier: " . $e->getMessage());
        
        // Provide a default identifier
        return new Guardian('default_identifier', $cache);
    }
}

Integration with Guardian

This exception is an integral part of the Guardian system's input validation. It ensures that the system always operates with valid identifiers, which is crucial for maintaining the integrity of rate limiting rules across different resources or actions.

Last updated