Saturday, September 24, 2011

Add Try::Tiny to Mouse or Moose


Here is a little snippet that shows how to extend Mouse (lightweight version of Moose) with Try::Tiny for better exception handling.

Here would be your application class:

package MyApp::Mouse;

use Mouse ();
use Mouse::Exporter;
use Try::Tiny;

Mouse::Exporter->setup_import_methods( 
	as_is => [qw[try catch finally]],
	also  => 'Mouse'
);

1;

Then you simply use MyApp::Mouse in place of the Mouse module for your classes:

package Foo;

use MyApp:::Mouse;

sub t {
	my ($self,$d) = @_;
	
	my $v = try {
		die "testing" if $d;
		'no';
	} catch {
		$_;
	}; 

	return $v;
}

1;

A simple test?

package Foo;

~$ perl -Mfeature=:5.12 -MFoo -e say Foo->new->t;
no

Of course this recipe works with Moose, simply replace the Mouse namespace with the Moose namespace and your in business.

1 comment:

  1. So, like.. are you with "Sara Mangus" because she looks like a dude and you're secretly gay?

    ReplyDelete