SyntaxStudy
Sign Up
PHP First-Class Exception Context
PHP Intermediate 5 min read

First-Class Exception Context

Exception Context Data

Enrich custom exceptions with context data (user ID, request ID, affected resource) that logging infrastructure can capture and surface in error reports.

Example
<?php
class ApiException extends RuntimeException {
    public function __construct(
        string $message,
        int $code,
        private readonly array $context = [],
        ?\Throwable $previous = null
    ) {
        parent::__construct($message, $code, $previous);
    }

    public function getContext(): array {
        return $this->context;
    }
}

throw new ApiException(
    "Payment declined",
    402,
    [
        "user_id"    => $user->id,
        "order_id"   => $order->id,
        "gateway"    => "stripe",
        "amount"     => $order->total,
    ]
);
Pro Tip

Include contextual data in custom exceptions to enable rich error reporting without polluting log messages with concatenated strings.