Sub::Exception - Code block with exception handler.
Usually, this module acts in use phase:
use Redis; use Sub::Exception redis_cmds => sub { MyException->throw($_) }; # when some exception occurred in this block, exception MyException threw. redis_cmds { my $redis = Redis->new; $redis->multi; ... # redis commands $redis->exec; };
Optionally have class methods exporting code block to specified package.
use Sub::Exception; Sub::Exception->export( name => 'redis_cmds', error_handler => sub { MyException->throw($_) }, package => 'Target::Package', );
Sub::Exception is code block generator that have own exception handler.
use Sub::Exception %name_handler_pairs;
This is main usage of this module. You can set multiple sub name and error handler pairs at once.
use Sub::Exception database_cmds => sub { die sprintf 'DB Error: %s', $_ }, redis_cmds => sub { die sprintf 'Redis Error: %s', $_ };
Above code is export two subs: database_cmds and redis_cmds into current package. And these subs has own error handlers.
database_cmds
redis_cmds
database_cmd { # some database functions };
Exceptions in this code block is caught by its error handler:
sub { die sprintf 'DB Error: %s', $_ }
So all exceptions wraps 'DB Error: ' prefix string and re-throw it.
Sub::Exception->export( name => 'redis_cmds', error_handler => sub { MyException->throw($_) }, package => 'Target::Package', );
Another way to export code blocks.
use Sub::Exception func => sub { ... };
is equivalent to:
use Sub::Exception; Sub::Exception->export( name => 'func', error_handler => sub { ... }, package => __PACKAGE__, );
This method is a bit verbosity but it's possible to export functions to any packages.
Daisuke Murase <typester@cpan.org>
Copyright (c) 2012 KAYAC Inc. All rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
The full text of the license can be found in the LICENSE file included with this module.
To install Sub::Exception, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Sub::Exception
CPAN shell
perl -MCPAN -e shell install Sub::Exception
For more information on module installation, please visit the detailed CPAN module installation guide.