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.
#
ConstructionUse run
static method:
#
FailureIn case of an exception, TryTo
returns an instance of Failure
.
You can use getCause(): Throwable
method to gets the underlying exception.
#
RecoveryCommon use case is recovery from failure. TryTo
gives you interesting option for that recover(string $throwable, callable $recovery): self
#
MethodsandThen(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): self
onSpecificFailure(string $throwable, callable $consumer): self
#
ExamplesTry to run operation, log error, and get default value - all in one simple object-oriented approach: