Hi
Am 2025-07-28 13:48, schrieb Rokas Šleinius:
Say I am implementing a job runner, I do its error handling, and I want
to
enrich the caught exception with additional helpful data for debugging.
In
this process I create a custom exception MyJobHandlerException, but the
trace of the new exception includes my handler code, which the end user
does not care about. I wish to overwrite the trace of the new
MyJobHandlerException instance with the trace from the originally
caught
exception, but I cannot.
In this case the original exception should be set as the `$previous`
exception for the `MyJobHandlerException` and then the resulting
exception includes both the original's and the new exception's stack
trace. Every exception handler worth its salt (including PHP's handler
for uncaught exceptions) will print the entire exception stack:
https://3v4l.org/2pc2Z
<?php
class MyJobHandlerException extends Exception {
public function __construct(string $message, public readonly int
$jobId, ?\Throwable $previous = null) {
parent::__construct($message, previous: $previous);
}
}
function execute_job(int $jobId) {
throw new \Exception('execute_job failed');
}
function runner() {
$jobId = 1;
try {
execute_job($jobId);
} catch (\Throwable $e) {
throw new MyJobHandlerException('Wrapping the exception',
$jobId, $e);
}
}
runner();
Best regards
Tim Düsterhus