Exception::getPrevious

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

Exception::getPreviousRetourne le Throwable précédent

Description

final public function Exception::getPrevious(): ?Throwable

Retourne le Throwable précédent (le troisième paramètre de la méthode Exception::__construct()).

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne le Throwable précédent si disponible, null sinon.

Exemples

Exemple #1 Exemple avec Exception::getPrevious()

Une boucle, on affiche et on capture les exceptions.

<?php
class MyCustomException extends Exception {}

function doStuff() {
    try {
        throw new InvalidArgumentException("Vous avez fait une erreur !", 112);
    } catch(Exception $e) {
        throw new MyCustomException("Un problème est survenu", 911, $e);
    }
}


try {
    doStuff();
} catch(Exception $e) {
    do {
        printf("%s:%d %s (%d) [%s]\n", $e->getFile(), $e->getLine(), $e->getMessage(), $e->getCode(), get_class($e));
    } while($e = $e->getPrevious());
}
?>

Résultat de l'exemple ci-dessus est similaire à :

/home/bjori/ex.php:8 Un problème est survenu (911) [MyCustomException]
/home/bjori/ex.php:6 Vous avez fait une erreur ! (112) [InvalidArgumentException]

Voir aussi

add a note

User Contributed Notes 1 note

up
14
harry at upmind dot com
7 years ago
/**
     * Gets sequential array of all previously-chained errors
     * 
     * @param Throwable $error
     * 
     * @return Throwable[]
     */
    function getChain(Throwable $error) : array
    {
        $chain = [];

        do {
            $chain[] = $error;
        } while ($error = $error->getPrevious());

        return $chain;
    }
To Top