Error Handling Rules

Error handling rules define how many errors are allowed before Guardian takes action. These rules help you manage and respond to failures in your application, allowing you to set thresholds for acceptable error rates.

Creating Error Handling Rules

You can create error handling rules using the ErrorHandlingRule class. This class provides a fluent interface for defining rules, making them easy to read and understand.

use Midnite81\Guardian\Rules\ErrorHandlingRule;
use Midnite81\Guardian\Enums\Interval;

// Allow 5 failures per minute, before throwing an error
$rule1 = ErrorHandlingRule::allowFailures(5)->perMinute();

// Equivalent to $rule1, but with explicit thenThrow()
$rule2 = ErrorHandlingRule::allowFailures(5)->perMinute()->thenThrow();

// Allow 50 failures per hour, without throwing an exception (for monitoring purposes)
$rule3 = ErrorHandlingRule::allowFailures(50)->perHour()->thenThrow(false);

// Allow 100 failures per day, before throwing an error
$rule4 = ErrorHandlingRule::allowFailures(100)->perDay();

// Allow 20 failures every 3 hours, before throwing an error
$rule5 = ErrorHandlingRule::allowFailures(20)->perInterval(Interval::HOUR, 3);

Important Note: Simply calling ErrorHandlingRule::allowFailures(5) without specifying a time interval does not create a functional rule. You must always specify a time interval for the rule to take effect. For example:

// This does nothing and will not be enforced
$ineffectiveRule = ErrorHandlingRule::allowFailures(5);

// This is a valid rule that will be enforced: it allows 5 failures per hour before throwing an error
$effectiveRule = ErrorHandlingRule::allowFailures(5)->perHour();

Available Methods

The ErrorHandlingRule class provides several methods to define your error handling rules:

Static Factory Method

  • allowFailures(int $failureThreshold): Starts the rule definition with the number of allowed failures. Note that this method alone is not sufficient to create a complete rule.

Time Interval Methods

  • perInterval(Interval $interval, int $duration = 1): Defines a custom time interval.

  • perMinute(): Sets the interval to one minute.

  • perMinutes(int $value): Sets the interval to a specified number of minutes.

  • perHour(): Sets the interval to one hour.

  • perHours(int $value): Sets the interval to a specified number of hours.

  • perDay(): Sets the interval to one day.

  • perDays(int $value): Sets the interval to a specified number of days.

Expiration Method

  • untilMidnightTonight(): Sets the rule to expire at midnight.

Action Method

  • thenThrow(bool $shouldThrow = true): Specifies whether to throw an exception when the failure threshold is exceeded.

Getter Methods

  • getFailureThreshold(): Returns the number of allowed failures.

  • getInterval(): Returns the interval enum value.

  • getDuration(): Returns the duration of the interval.

  • getUntil(): Returns the expiration time, if set.

  • shouldThrow(): Returns whether an exception should be thrown when the threshold is exceeded.

  • getTotalSeconds(): Returns the total number of seconds for the interval.

  • getKey(string $prefix = '', string $suffix = ''): Generates a unique key for the rule.

The thenThrow() Method

The thenThrow() method determines whether Guardian should throw an exception when the failure threshold is exceeded. By default, it's set to true.

// Will throw an exception after 10 failures per hour
$rule1 = ErrorHandlingRule::allowFailures(10)->perHour();

// Equivalent to the above
$rule2 = ErrorHandlingRule::allowFailures(10)->perHour()->thenThrow();

// Will not throw an exception, even if more than 10 failures occur per hour
$rule3 = ErrorHandlingRule::allowFailures(10)->perHour()->thenThrow(false);

Note: Using thenThrow(false) effectively means that Guardian will track the number of failures but won't take any action when the threshold is exceeded. This can be useful for logging or monitoring purposes, but it doesn't provide any automatic error handling. Use this option with caution, as it may lead to ignoring critical errors in your application.

Using Error Handling Rules

Once you've defined your rules, you can add them to your Guardian instance:

use Midnite81\Guardian\Factories\GuardianFactory;
use Midnite81\Guardian\Store\RedisStore;

$guardian = GuardianFactory::create(
    'my-api',
    new RedisStore($redisOptions),
    null, // Rate limiting rules (null in this example)
    [
        ErrorHandlingRule::allowFailures(5)->perMinute(),
        ErrorHandlingRule::allowFailures(50)->perHour(),
    ]
);

These rules will now be applied to all requests handled by this Guardian instance.

Best Practices

  1. Always specify a time interval: Remember that an error handling rule is not complete without a time interval. Always use methods like perMinute(), perHour(), etc., to define the time frame for your rule.

  2. Combine rules: Use multiple rules to create more comprehensive error handling strategies. For example, you might allow a higher number of failures per day, but set a lower threshold for per-minute failures to catch sudden spikes in errors.

  3. Use appropriate intervals: Choose intervals that make sense for your application. For critical operations, per-minute or per-hour limits might be appropriate, while for less critical operations, per-day limits might suffice.

  4. Consider error severity: You might create different rules for different types of errors. Critical errors might have lower thresholds than less severe errors.

  5. Use thenThrow(false) judiciously: While thenThrow(false) can be useful for monitoring, be cautious about using it for critical errors. It's often better to handle errors actively rather than simply tracking them.

  6. Monitor and adjust: Regularly review your error handling rules and adjust them based on your application's performance and error patterns.

By effectively using error handling rules, you can create more robust applications that gracefully handle failures and provide better reliability for your users.

Last updated