Failure is a soft or unthrown exception, usually generated by calling
&fail. It acts as a wrapper around an Exception object.
Sink (void) context causes a Failure to throw, i.e. turn into a normal exception.
Checking a Failure for truth (with the
Bool method) or definedness (with the
defined method) marks the failure as handled, and causes it not to throw in sink context anymore.
You can call the
handled method to check if a failure has been handled.
Calling methods on unhandled failures propagates the failure. The specification says the result is another
Failure, in Rakudo it causes the failure to throw.
method new(Failure: --> Failure)
Returns a new
Failure instance with the given payload. The latter can be either an Exception or a payload for an
Exception. A typical payload would be a
Str with an error message. A list of payloads is also accepted.
my = Failure.new(now.DateTime, 'WELP‼');say ;CATCH# OUTPUT: «X::AdHoc: 2017-09-10T11:56:05.477237ZWELP‼␤»
method handled(Failure: --> Bool)
True for handled failures,
sub f() ; my = f; say .handled; # OUTPUT: «False␤»
handled method is an lvalue, which means you can also use it to set the handled state:
sub f()my = f;.handled = True;say .handled; # OUTPUT: «True␤»
method exception(Failure: --> Exception)
Returns the Exception object that the failure wraps.
sub failer() ;my = failer;my = .exception;put "$ex.^name(): $ex";# OUTPUT: «X::AdHoc: Failed␤»
method self(Failure: --> Failure)
If the invocant is a handled
Failure, returns it as is. If not handled, throws its Exception. Since Mu type provides
.self for every class, calling this method is a handy way to explosively filter out Failures:
my = '♥'.Int;# $num1 now contains a Failure object, which may not be desirablemy = '♥'.Int.self;# .self method call on Failure causes an exception to be thrownmy = '42'.Int.self;# Int type has a .self method, so here $num3 has `42` in it(my = '♥'.Int).so;say .self; # OUTPUT: «(HANDLED) Cannot convert string to number…»# Here, Failure is handled, so .self just returns it as is
multi method Bool(Failure: --> Bool)
False, and marks the failure as handled.
sub f() ; my = f; say .handled; .Bool; say .handled;# OUTPUT: «False␤# True␤»
multi method defined(Failure: --> Bool)
False (failures are officially undefined), and marks the failure as handled.
sub f() ; my = f; say .defined; # OUTPUT: «False␤»