Laravel 9 report() with context

34 Views Asked by At

I would like to log context of exception as current data in some variables. But repost() handler which I use to log exceptions does not support context parameters. Is there any other way to do it?

try {  
   // process the points
   $customerPointsService->subtractPointsForRewardReservation($customerReward);
} catch(\Throwable $e) {
   report($e);  
   // I would like to log also some variable values
   return $this->sendJsonErrorWithCorrectStatusCode("Customer point subtraction failed.", [], 422);
}
1

There are 1 best solutions below

0
Jeyhun Rashidov On BEST ANSWER

Create a custom exception:

class ContextualException extends \Exception {
    protected $context;

    public function __construct($message = "", $code = 0, Throwable $previous = null, $context = []) {
        parent::__construct($message, $code, $previous);
        $this->context = $context;
    }

    public function getContext() {
        return $this->context;
    }
}
try {
    // If an error occurs
    throw new ContextualException("Error message", 0, null, ['variable' => $variableValue]);
} catch (ContextualException $e) {
    report($e);
    // Access context data
    $context = $e->getContext();
    // Log context or do something with it
    return $this->sendJsonErrorWithCorrectStatusCode("Customer point subtraction failed.", [], 422);
}