Last active
April 17, 2020 17:15
-
-
Save vendethiel/3327f7d30be00a085e1734f2215f2b38 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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