Created
February 18, 2013 19:07
-
-
Save arisawa/4979784 to your computer and use it in GitHub Desktop.
ありがちな処理を Exception::Tiny と Try::Lite で
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
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
use feature qw/say/; | |
use utf8; | |
use Exception::Tiny; | |
package MyException; | |
use parent 'Exception::Tiny'; | |
use Class::Accessor::Lite ( | |
ro => [qw/ error_code /], | |
); | |
package Controller; | |
use Try::Lite; | |
use Log::Minimal; | |
use Data::Dumper; | |
sub index { | |
my $params = shift; | |
my $result = try { | |
Validator->validate($params); | |
Model->create_foo($params); | |
} | |
'MyException' => sub { $@ }, | |
'*' => sub { | |
critf('unknown error:%s', $@); | |
render('500.tt'); | |
}; | |
if ( MyException->caught($result) ) { | |
warnf('error_code:%s', $result->error_code); | |
return render('error.tt', +{ | |
error_code => $result->error_code, | |
}); | |
} | |
} | |
sub render { | |
say 'tmpl:', shift; | |
say Dumper shift; | |
} | |
package Validator; | |
sub validate { | |
MyException->throw( | |
message => 'Error occured: validate params', | |
error_code => 'validate_error', | |
); | |
} | |
package Model; | |
sub prepare { | |
MyException->throw( | |
message => 'Error occured: prepare to create', | |
error_code => 'prepare_error', | |
); | |
} | |
sub create_foo { | |
prepare(); | |
DataSource->create; | |
} | |
package DataSource; | |
use Try::Lite; | |
use Log::Minimal; | |
sub create { | |
dbi_do(); | |
} | |
sub dbi_do { die 'DB error' } | |
package main; | |
use Test::Mock::Guard qw/mock_guard/; | |
my $g1 = mock_guard(Validator => +{ | |
validate => +{}, | |
}); | |
my $g2 = mock_guard(Model => +{ | |
prepare => +{}, | |
}); | |
# my $g3 = mock_guard(Model => +{ | |
# create => sub { | |
# MyException->throw( | |
# message => 'Error occured: create', | |
# error_code => 'create_error', | |
# ); | |
# }, | |
# }); | |
Controller->index; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment