CrashGuard

Lightweight exception capture, deduplication, and notification for Laravel

1.0.0 GitHub ActionsMITPHP ^8.4Laravel ^12.0 | ^13.0

Capture exceptions, deduplicate by fingerprint, persist to the database, and dispatch queued notifications via Slack and/or Mail — with a circuit breaker, PHP 8 attribute-based classification, and a full report lifecycle.

Requirements

Core Package
  • PHP ^8.4
  • Laravel ^12.0 | ^13.0

Install with Composer

composer require t-labs-co/crash-guard

CrashGuard captures exceptions (or plain string messages), deduplicates them by fingerprint, persists them to the database, and dispatches queued notifications via Slack and/or Mail. It ships with a circuit breaker to prevent alert floods, PHP 8 attribute-based exception classification, a ReportContextDTO for typed context, and a complete report lifecycle (resolve, ignore, snooze).


Why not Laravel’s report()?

Laravel’s report() helper is great for sending exceptions to your log channels. CrashGuard is for when you need more: deduplication so you’re not spammed by the same error, a circuit breaker to prevent alert floods, structured notifications to Slack or Mail, and a lifecycle to resolve, ignore, or snooze reports over time.

Laravel’s report() CrashGuard
Exception capture ✅ report() helper / Handler ✅ crash_report() + CrashGuard facade
Deduplication None ✅ Fingerprint-based, configurable window
Alert flood protection None ✅ Circuit breaker with rolling window and daily caps
Notification channels None ✅ Slack, Mail, extensible via ChannelRegistry
Exception classification Manual checks in handler ✅ PHP 8 attributes or marker interfaces
Report lifecycle None ✅ Resolve, ignore, snooze, mark-as-read
Context tracking Context array in logs ✅ Typed ReportContextDTO with user, IP, route
Runtime toggle Config flag ✅ CrashGuard::enable() / disable()

Choose native report() if you only need to log exceptions. Choose CrashGuard if you want deduplication, alert protection, multi-channel notifications, and a full report lifecycle.


Get started in minutes

Follow these steps to install the package, hook it into your exception handler, and verify it works.

1. Install the package

composer require t-labs-co/crash-guard

This adds the package to your composer.json and installs all dependencies.

2. Run the migrations

php artisan migrate

The package creates the crash_reports table for storing deduplicated exception reports with their full lifecycle data.

3. Hook into the exception handler

Add CrashGuard to bootstrap/app.php so every unhandled exception is captured automatically:

use Illuminate\Foundation\Application;
use TLabsCo\CrashGuard\Facades\CrashGuard;

return Application::configure(basePath: dirname(__DIR__))
    ->withExceptions(function (\Illuminate\Foundation\Exceptions\Handler $exceptions) {
        $exceptions->report(function (\Throwable $e) {
            CrashGuard::report($e);
        });
    })
    ->create();

Now every unhandled exception flows through CrashGuard’s deduplication, circuit breaker, and notification pipeline.

4. Configure your notification channels

Set the minimum environment variables in your .env:

CRASH_GUARD_ENABLED=true
CRASH_GUARD_CHANNELS=slack,mail
CRASH_GUARD_SLACK_WEBHOOK=https://hooks.slack.com/services/xxx/yyy/zzz
CRASH_GUARD_MAIL_TO=alerts@example.com

5. Smoke-test the integration

php artisan crash-guard:test

This command runs through all report cases — exception, string, silent, urgent, debug, resolve, read, ignore, pause, and disabled — so you can verify the entire integration end-to-end.

6. Check the status

php artisan crash-guard:status

Example output:

CrashGuard Status

  Enabled:          YES
  Mode:             normal
  Dedup window:     60 minutes
  Channels:         slack, mail
  Circuit breaker:  enabled (threshold: 10, cooldown: 300s)
  Pending reports:  4
  Total reports:    127
  Prune after:      30 days
  Scheduling:       disabled

Features

Fingerprint deduplication

Each unique error produces one database row. The fingerprint is derived from the exception class, message, file, and line. When the same error recurs, occurrence_count increments and last_seen_at updates, but no new notification is sent within the dedup window (default 60 minutes).

Circuit breaker

The circuit breaker prevents alert floods with three independent guards:

  • Cooldown window — once a fingerprint exceeds the threshold hits within the rolling cooldown window, notifications are silenced for the remainder
  • Per-fingerprint daily limit — if a fingerprint exceeds the daily limit on a calendar day, it is silenced until midnight
  • Global daily limit — if total occurrences across all fingerprints exceeds the global daily limit, all non-urgent notifications are silenced until midnight

Reports with Urgent mode bypass all circuit checks and always notify.

PHP 8 attribute API

Apply attributes directly to exception classes to control their reporting behavior:

use TLabsCo\CrashGuard\Attributes\UrgentCrashReport;
use TLabsCo\CrashGuard\Attributes\SilentCrashReport;
use TLabsCo\CrashGuard\Attributes\IgnoreCrashReport;

#[UrgentCrashReport]
class DatabaseConnectionLostException extends \RuntimeException {}

#[SilentCrashReport]
class ExternalApiTimeoutException extends \RuntimeException {}

#[IgnoreCrashReport]
class BotScanException extends \RuntimeException {}

Typed context

Attach structured context to reports using ReportContextDTO:

use TLabsCo\CrashGuard\Core\Reporting\Application\DTOs\ReportContextDTO;
use TLabsCo\CrashGuard\Facades\CrashGuard;

$context = new ReportContextDTO(
    userId: (string) auth()->id(),
    userEmail: auth()->user()?->email,
    ip: request()->ip(),
    route: request()->route()?->getName(),
    extra: ['order_id' => $orderId],
);

CrashGuard::reportWithContext($exception, $context);

Report lifecycle

Manage reports over time with resolve, ignore, snooze, and mark-as-read:

use TLabsCo\CrashGuard\Facades\CrashGuard;

CrashGuard::resolve($report);   // Mark resolved, reset circuit breaker counter
CrashGuard::read($report);      // Mark as read (no status change)
CrashGuard::ignore($report);    // Suppress future notifications for this fingerprint
CrashGuard::pause($report, now()->addHours(4));  // Snooze notifications until a datetime

Multi-channel notifications

Slack (Block Kit) and Mail are built in. Extend with custom channels by implementing NotificationChannelContract and registering them with ChannelRegistry:

use TLabsCo\CrashGuard\Core\Reporting\Infrastructure\Notifications\ChannelRegistry;

$this->app->afterResolving(ChannelRegistry::class, function (ChannelRegistry $registry) {
    $registry->register('discord', new DiscordCrashChannel());
});

Usage

Via the Facade

use TLabsCo\CrashGuard\Facades\CrashGuard;

CrashGuard::report(new \RuntimeException('Payment failed'));
CrashGuard::report($exception, ['order_id' => $order->id]);
CrashGuard::report('Unexpected state encountered in payment flow');
CrashGuard::reportAsUrgent($exception);   // Bypass dedup and circuit breaker
CrashGuard::reportAsDebug($exception);    // Stored in DB only, no notifications

Via the Global Helper

crash_report(new \RuntimeException('Something failed'));
crash_report('Unexpected state', ['context_key' => 'value']);

Via Dependency Injection

Type-hint CrashGuardContract for easy mocking in tests:

use TLabsCo\CrashGuard\Core\Reporting\Application\Contracts\CrashGuardContract;

class PaymentService
{
    public function __construct(private readonly CrashGuardContract $crashGuard) {}

    public function charge(Order $order): void
    {
        try {
            // ...
        } catch (\Throwable $e) {
            $this->crashGuard->report($e, ['order_id' => $order->id]);
        }
    }
}

Runtime Toggle

CrashGuard::disable();   // Stop capturing (e.g. during maintenance)
CrashGuard::enable();    // Re-enable
CrashGuard::isEnabled(); // bool

Exception Classification

Priority Chain

Priority Rule Effect
1 (highest) ShouldReportToCrashGuard / #[ReportToCrashGuard] Always report — overrides ignore list
2 ShouldIgnoreCrashReport / #[IgnoreCrashReport] Always skip
3 ignored_exceptions config list Skip
4 (default) — Report normally

Ignored Exceptions (default)

The following are ignored out of the box: AuthenticationException, ValidationException, ThrottleRequestsException, NotFoundHttpException, MethodNotAllowedHttpException, AuthorizationException, TokenMismatchException, ModelNotFoundException.

Add your own in config/crash-guard.php:

'ignored_exceptions' => [
    \App\Exceptions\MyExpectedException::class,
],

Report Mode

Mode Behaviour
normal Standard reporting and notification
debug Stored in DB only, no notifications
urgent Bypasses dedup and the circuit breaker — always notifies

Mode resolution order (highest wins): explicit $mode argument → #[UrgentCrashReport] on the exception → #[DebugCrashReport] on the exception → CRASH_GUARD_MODE global default.


Artisan commands reference

Command Description
php artisan crash-guard:test Smoke-test all report cases end-to-end
php artisan crash-guard:prune Delete resolved/ignored reports older than configured threshold
php artisan crash-guard:reset Reset circuit breaker counters
php artisan crash-guard:status Show current configuration and report statistics
php artisan crash-guard:help Display help and usage information

Configuration

Publish the configuration file to customize behavior:

php artisan vendor:publish --tag=crash-guard-config

Publish the mail view to customize the email template:

php artisan vendor:publish --tag=crash-guard-views

Key Environment Variables

Variable Default Description
CRASH_GUARD_ENABLED true Master on/off switch
CRASH_GUARD_DEDUP_MINUTES 60 Suppress duplicate notifications within this window
CRASH_GUARD_CHANNELS slack,mail Active notification channels
CRASH_GUARD_SLACK_WEBHOOK — Slack incoming webhook URL
CRASH_GUARD_MAIL_TO — Recipient email address(es)
CRASH_GUARD_PRUNE_DAYS 30 Prune resolved/ignored reports older than N days
CRASH_GUARD_CIRCUIT_BREAKER_THRESHOLD 10 Max hits within cooldown before silencing
CRASH_GUARD_CIRCUIT_BREAKER_COOLDOWN 300 Cooldown window in seconds
CRASH_GUARD_CIRCUIT_BREAKER_DAILY_LIMIT 10 Max hits per fingerprint per calendar day
CRASH_GUARD_CIRCUIT_BREAKER_GLOBAL_DAILY_LIMIT 50 Max total hits across all fingerprints per day

For complete documentation, see the Usage Examples and Testing Guide on GitHub.

Why I built it

Laravel's built-in report() helper sends exceptions to your log channels, but there's no deduplication, no alert flood protection, and no way to track or manage error reports over time. CrashGuard fills that gap by capturing exceptions, deduplicating them by fingerprint, protecting against notification storms with a circuit breaker, and providing a full lifecycle to resolve, ignore, or snooze reports — all with Slack and Mail notifications out of the box.

Hire me for Laravel error monitoring and notification system work

Need a package tailored to your application? From recurring Laravel maintenance tasks to reusable components, I can help design, build, and review production-ready solutions.

Discuss your project