TryTo
The TryTo control gives us the ability to write safe code without focusing on try-catch blocks in the presence of exceptions.
TryTo wraps given callable and catch any Throwable that will occur while executing it.
Remember that TryTo will may re-throw exception when calling get() method. You can prevent from this using isSuccess() or isFailure() methods.
Construction#
Use run static method:
Failure#
In case of an exception, TryTo returns an instance of Failure.
You can use getCause(): Throwable method to gets the underlying exception.
Recovery#
Common use case is recovery from failure. TryTo gives you interesting option for that recover(string $throwable, callable $recovery): self
Methods#
andThen(callable $callable): self- allow to chain next operationandFinally(callable $callable): self- run given $callable whatever the result isonSuccess(callable $consumer): self- run given $consumer with success value as an argumentonFailure(callable $consumer): selfonSpecificFailure(string $throwable, callable $consumer): self
Examples#
Try to run operation, log error, and get default value - all in one simple object-oriented approach: