ComponentesFuture::failed

Future::failed

(PHP 8.6+, True Async 1.0)

php
public static function failed(\Throwable $throwable): Future

Crea un Future que se completa inmediatamente con el error especificado. Llamar a await() en dicho Future lanzará la excepción proporcionada.

Parámetros

throwable — la excepción con la que se completará el Future.

Valor de retorno

Future — un Future completado con un error.

Ejemplos

Ejemplo #1 Crear un Future con un error

php
<?php

use Async\Future;
use Async\FutureState;

$future = Future::failed(new \RuntimeException("Error de carga"));

var_dump($future->isCompleted()); // bool(true)

try {
    $future->await();
} catch (\RuntimeException $e) {
    echo "Capturado: " . $e->getMessage() . "\n";
    // Capturado: Error de carga
}

Ejemplo #2 Uso para retorno temprano de error

php
<?php

use Async\Future;
use Async\FutureState;

function connectToService(string $host): Future {
    if (empty($host)) {
        return Future::failed(
            new \InvalidArgumentException("El host no puede estar vacío")
        );
    }

    $state = new FutureState();

    \Async\spawn(function() use ($state, $host) {
        try {
            $state->complete(performConnection($host));
        } catch (\Throwable $e) {
            $state->error($e);
        }
    });

    return new Future($state);
}

$future = connectToService('');
$future
    ->catch(function(\Throwable $e) {
        echo "Error: " . $e->getMessage() . "\n";
    })
    ->ignore();

Ver también