Some API suggestions
I've some suggestions for the API after trying this a bit. Basically, I'm wondering what you think about something like this:
Attempt::call($someCallable)
->forAll($onSuccess)
->always($always) // Finally semantics (called regardless of success/failure)
->throwIfFailed()
;
This would be equivalent to:
try {
$rs = $someCallable();
$onSuccess($rs);
} finally {
$always();
}
Not sure if this is already supported in another way, but I haven't found anything. What do you think?
@schmittjoh I added forAll() (see the other issue), and I like the other suggestions. I was just wondering about the following.
-
throwIfFailed()could be achieved by callingget()which will return the value, or throw if there was an exception. Not sure if it's worth adding an extra method for this? -
always($callable)This callable cannot be passed a value (I guess that's ok), but what should happen if thealways()callable throws? I think the best thing would be to not catch this exception in the library and let the user handle it, but your example code seems to suggest otherwise?
Thanks for the addition, good job.
I believe get() is what I'm using right now. It's not terribly necessary to have the extra method, it would improve readability for someone else though. Not sure if there is also a use-case for a different return value, i.e. throwIfFailed returning the Attempt. Overall, more a nice-to-have thing, not a must-have :)
Regarding the other method, yeah I think it's a good idea to let the user handle it (or letting him make sure he does not throw one).