--- On Wed, 7/4/10, Lutz Gehlen <[email protected]> wrote:
> From: Lutz Gehlen <[email protected]>
> I understand that I can build a hierarchy of exception
> classes using
> Exception::Class. But when I throw an exception I still
> have to
> assemble the error message there, e.g.:
>
> if(!defined($foo)) {
> My::Exception::Class->throw
> ('Variable foo is undefined. We are doomed.');
> }
You mentioned aliasing, but I want to give an explicit example so people can
see what's going on. I'll also assert that we're using the new // operator
because this can make a lot of the boilerplate go away:
$foo // throw_undef 'Variable foo is undefined. We are doomed';
That's much nicer (which is important. It's not just sugar!)
> What I need a central place for is the definition of the
> actual
> error messages. With my module Exception::EasyThrow, I can
> write at
> the beginning of my module:
>
> use Exception::EasyThrow
> (var_ud => 'Variable %s is undefined. We
> are doomed.',
> ... => ...);
>
> and then later
>
> var_ud('foo') if(!defined($foo));
Then why not supply a patch for Exception::Class to allow it handle formats?
Note, in your code above, you can still have different error messages in
different packages. You've made things a touch easier, but not really solved
the underlying problem. What about this proposal for Exception::Class?
package My::Exceptions;
use Exception::Class (
'MyException',
'IORead' => {
isa => 'MyException',
alias => 'throw_io_read',
format => [ 'Cannot open %s for reading: %s' ],
},
);
And then:
use My::Exceptions 'throw_io_read';
open my $fh, '<', $filename or throw_io_read $filename, $!;
Presumably the format should try to determine the number of conversions in the
format and perhaps the alias could generate a sub with a corresponding
prototype like 'sub throw_io_read($$)'. That might give you a touch of
compile-time safety. Haven't really thought too carefully about this, though.
With this strategy, you really *do* get to avoid both varying messages and
verbosity.
Cheers,
Ovid
--
Buy the book - http://www.oreilly.com/catalog/perlhks/
Tech blog - http://blogs.perl.org/users/ovid/
Twitter - http://twitter.com/OvidPerl
Official Perl 6 Wiki - http://www.perlfoundation.org/perl6