Coroutine::getException

(PHP 8.6+, True Async 1.0)

public Coroutine::getException(): mixed

Restituisce l’eccezione che si è verificata nella coroutine. Se la coroutine si è completata con successo o non è ancora completata, restituisce null. Se la coroutine è stata annullata, restituisce un oggetto AsyncCancellation.

Valore di ritorno

mixed – l’eccezione o null.

Errori

Lancia RuntimeException se la coroutine è attualmente in esecuzione.

Esempi

Esempio #1 Completamento con successo

<?php

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

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

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

Esempio #2 Completamento con errore

<?php

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

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

try {
    await($coroutine);
} catch (RuntimeException $e) {
    // Catturato durante await
}

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

Esempio #3 Coroutine annullata

<?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)

Vedi anche