Library contents

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

  1. Start with A conversion fails, then gets wrapped
  2. Do this Read the previous cause
  3. Result Original conversion failure
The outer message explains what the caller was doing. The cause preserves the underlying failure.

Syntax

PHP 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.

From the programdeclare(strict_types=1)
First output lineimport failed
lesson.php
<?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";
    }
}
Output
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

Advertisements

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.

GivenBatch → missing record
Worked resultMissing record

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.

GivenReport → invalid count
Worked resultInvalid count