PHP Throwable::getPrevious
Throwable::getPrevious returns the exception supplied as the previous cause. Wrapping an exception can add context while preserving the original message.
A simple example
Throwable::getPrevious
- Start with A conversion fails, then gets wrapped
- Do this Read the previous cause
- Result Original conversion failure
Syntax
throw new RuntimeException($message, 0, $cause)
Run this example in PHP
Save the program as lesson.php. Use PHP 8.2 or later.
php lesson.php
Preserve the original reason for an import failure
A high-level import fails because a lower-level step could not complete. Retain the original cause when adding context so the person diagnosing the batch can still find the first failure.
<?php
declare(strict_types=1);
try {
try {
throw new InvalidArgumentException('invalid quantity');
} catch (InvalidArgumentException $cause) {
throw new RuntimeException('import failed', 0, $cause);
}
} catch (RuntimeException $error) {
for ($entry = $error; $entry !== null; $entry = $entry->getPrevious()) {
echo $entry->getMessage() . "\n";
}
}
import failed invalid quantity
The chain ends when getPrevious returns null. This example walks it explicitly so a caller can see both the import context and the invalid field.
PHP documentation for Throwable::getPrevious
Trace a missing shipment record
An importer wraps a missing-record error with a message about the batch. Read the message on the preserved underlying cause to identify what the operator should fix.
Trace a malformed count
A report worker wraps a bad numeric field in a higher-level error. Read the message on the preserved underlying cause to identify what the operator should fix.