Scope::setChildScopeExceptionHandler

(PHP 8.6+, True Async 1.0)

public function setChildScopeExceptionHandler(callable $exceptionHandler): void

Imposta un gestore delle eccezioni per le eccezioni lanciate negli scope figli. Quando uno scope figlio termina con un errore, questo gestore viene chiamato, impedendo all’eccezione di propagarsi allo scope genitore.

Parametri

exceptionHandler — la funzione di gestione delle eccezioni per gli scope figli. Accetta un \Throwable come argomento.

Valore di ritorno

Non viene restituito alcun valore.

Esempi

Esempio #1 Cattura degli errori degli scope figli

<?php

use Async\Scope;

$parentScope = new Scope();

$parentScope->setChildScopeExceptionHandler(function(\Throwable $e) {
    error_log("Errore nello scope figlio: " . $e->getMessage());
});

$childScope = Scope::inherit($parentScope);

$childScope->spawn(function() {
    throw new \RuntimeException("Errore dello scope figlio");
});

$childScope->awaitCompletion();
// Errore gestito, non si propaga a $parentScope

Esempio #2 Isolamento degli errori tra moduli

<?php

use Async\Scope;

$appScope = new Scope();

$appScope->setChildScopeExceptionHandler(function(\Throwable $e) {
    error_log("[App] Errore del modulo: " . $e->getMessage());
});

// Ogni modulo nel proprio scope
$authScope = Scope::inherit($appScope);
$cacheScope = Scope::inherit($appScope);

$authScope->spawn(function() {
    // Un errore qui non influenzera' $cacheScope
    throw new \RuntimeException("Autenticazione fallita");
});

$cacheScope->spawn(function() {
    echo "La cache funziona correttamente\n";
});

$appScope->awaitCompletion();

Vedi anche