ComponentsFuture::failed

Future::failed

(PHP 8.6+, True Async 1.0)

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

Creates a Future that is immediately completed with the specified error. Calling await() on such a Future will throw the provided exception.

Parameters

throwable — the exception with which the Future will be completed.

Return value

Future — a completed Future with an error.

Examples

Example #1 Creating a Future with an error

php
<?php

use Async\Future;
use Async\FutureState;

$future = Future::failed(new \RuntimeException("Loading error"));

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

try {
    $future->await();
} catch (\RuntimeException $e) {
    echo "Caught: " . $e->getMessage() . "\n";
    // Caught: Loading error
}

Example #2 Using for early error return

php
<?php

use Async\Future;
use Async\FutureState;

function connectToService(string $host): Future {
    if (empty($host)) {
        return Future::failed(
            new \InvalidArgumentException("Host cannot be empty")
        );
    }

    $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();

See also