Coroutine::getException

(PHP 8.6+, True Async 1.0)

public Coroutine::getException(): mixed

Retourne l’exception survenue dans la coroutine. Si la coroutine s’est terminée avec succès ou n’est pas encore terminée, retourne null. Si la coroutine a été annulée, retourne un objet AsyncCancellation.

Valeur de retour

mixed – l’exception ou null.

Erreurs

Lance une RuntimeException si la coroutine est en cours d’exécution.

Exemples

Exemple #1 Terminaison réussie

<?php

use function Async\spawn;
use function Async\await;

$coroutine = spawn(function() {
    return "success";
});

await($coroutine);
var_dump($coroutine->getException()); // NULL

Exemple #2 Terminaison avec erreur

<?php

use function Async\spawn;
use function Async\await;

$coroutine = spawn(function() {
    throw new RuntimeException("test error");
});

try {
    await($coroutine);
} catch (RuntimeException $e) {
    // Interceptée lors de l'await
}

$exception = $coroutine->getException();
var_dump($exception instanceof RuntimeException); // bool(true)
var_dump($exception->getMessage());                // string(10) "test error"

Exemple #3 Coroutine annulée

<?php

use function Async\spawn;
use function Async\suspend;

$coroutine = spawn(function() {
    Async\delay(10000);
});

suspend();
$coroutine->cancel();
suspend();

$exception = $coroutine->getException();
var_dump($exception instanceof \Async\AsyncCancellation); // bool(true)

Voir aussi