Skip to content

Instantly share code, notes, and snippets.

@gfldex
Created July 31, 2020 21:00
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 gfldex/bff98783b6bce7bc326d3b881b291da2 to your computer and use it in GitHub Desktop.
Save gfldex/bff98783b6bce7bc326d3b881b291da2 to your computer and use it in GitHub Desktop.
use v6.d;
multi sub trait_mod:<is>(Exception:U $ex, :$refineable) {
$ex.HOW.add_attribute($ex, Attribute.new(:name<@refinements>, :type(Array), :package($ex)));
$ex.HOW.add_method($ex, ‚refine‘, my method (&cond, &message) {
$ex.WHO::<@refinements>.append: &cond, &message;
state $wrapped;
$ex.HOW.find_method($ex, ‚message‘).wrap(my method {
my @refinements := self.WHO::<@refinements>;
for @refinements -> &cond, &message {
if cond(self) {
return message(self);
}
}
nextsame
}) unless $wrapped;
$wrapped = True;
});
$ex.HOW.add_method($ex, ‚refinements‘, my method {
$ex.WHO::<@refinements>;
});
}
class X::Shell::CommandNotFound is Exception is refineable {
has $.cmd;
has $.path;
method message {
$.path
?? „The shell command ⟨$.cmd⟩ was not found in ⟨$.path⟩.“
!! „The shell command ⟨$.cmd⟩ was not found.“
}
}
X::Shell::CommandNotFound.refine({.cmd eq ‚find‘}, {„Please install ⟨{.cmd}⟩ in ⟨{.path}⟩.“});
X::Shell::CommandNotFound.refine({.cmd eq ‚raku‘}, {„Please run `apt install rakudo`.“});
my $x1 = X::Shell::CommandNotFound.new(:cmd(‚find‘), :path(%*ENV<PATH>));
my $x2 = X::Shell::CommandNotFound.new(:cmd(‚raku‘), :path(%*ENV<PATH>));
my $x3 = X::Shell::CommandNotFound.new(:cmd(‚sendmail‘), :path(%*ENV<PATH>));
say $x1.message; # custom message for find
say $x2.message; # custom message for raku
say $x3.message; # default message
# LEAVE slurp($*PROGRAM).say;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment