Skip to content

Instantly share code, notes, and snippets.

@vendethiel
Last active April 17, 2020 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vendethiel/3327f7d30be00a085e1734f2215f2b38 to your computer and use it in GitHub Desktop.
Save vendethiel/3327f7d30be00a085e1734f2215f2b38 to your computer and use it in GitHub Desktop.
class X::DivideByZero is Exception {}
class X::UnknownRestart is Exception {
has $.name;
method message { "Unknown restart: $.name" }
}
my %*BOUND;
sub restart-case(Code $code, *%handlers) {
temp %*BOUND = %*BOUND, %handlers;
$code()
}
sub invoke-restart($name) {
if %*BOUND{$name}:exists {
%*BOUND{$name}($*CURRENT-EXCEPTION)
} else {
X::UnknownRestart.new(:$name).throw; # ...
}
}
sub handler-bind(Code $code, %exceptions) {
my $ret;
{
use fatal;
$ret = $code();
CATCH {
when %exceptions{.WHAT}:exists {
my $*CURRENT-EXCEPTION = $_;
$ret = %exceptions{.WHAT}();
}
}
}
return $ret;
}
sub f() {
restart-case(-> {
X::DivideByZero.new.throw;
}, default => {; 1 }, bad => {; .rethrow });
}
say handler-bind(-> { f() }, :{
(X::DivideByZero) => -> { invoke-restart('default') },
(X::AdHoc) => -> { invoke-restart('bad') },
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment