<U, E is Throwable>
Execute a callable and transform the result into an Result
.
It will be a Result\Ok
containing the result or, if it threw an exception
matching $exceptionClass, a Result\Err
containing the exception.
Successful execution:
self::assertEq(Result\ok(3), Result\trap(fn () => 3));
Checked exception:
$x = Result\trap(fn () => new \DateTimeImmutable("2020-30-30 UTC"));
self::assertTrue($x->isErr());
$x->unwrap();
// @throws Exception Failed to parse time string (2020-30-30 UTC) at position 6 (0): Unexpected character
Unchecked exception:
Result\trap(fn () => 1/0);
// @throws DivisionByZeroError Division by zero
Parameters | |||
---|---|---|---|
callable(mixed...): U
|
$callback |
# | |
class-string<E>
|
$exceptionClass = Exception::class |
# |
Returns | |
---|---|
Result<U, E>
|
Throws | |
---|---|
Throwable |