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.
Enrich custom exceptions with context data (user ID, request ID, affected resource) that logging infrastructure can capture and surface in error reports.
<?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,
]
);
Include contextual data in custom exceptions to enable rich error reporting without polluting log messages with concatenated strings.