0fec11a02763427d8b6862d3cce0a52534c8f6cd
[dbsrgits/DBIx-Class.git] / t / 34exception_action.t
1 use strict;
2 use warnings;
3
4 use Test::More;
5 use lib qw(t/lib);
6 use DBICTest;
7
8 # Set up the "usual" sqlite for DBICTest
9 my $schema = DBICTest->init_schema;
10
11 # This is how we're generating exceptions in the rest of these tests,
12 #  which might need updating at some future time to be some other
13 #  exception-generating statement:
14
15 sub throwex { $schema->resultset("Artist")->search(1,1,1); }
16 my $ex_regex = qr/Odd number of arguments to search/;
17
18 # Basic check, normal exception
19 eval { throwex };
20 my $e = $@; # like() seems to stringify $@
21 like($@, $ex_regex);
22
23 # Re-throw the exception with rethrow()
24 eval { $e->rethrow };
25 isa_ok( $@, 'DBIx::Class::Exception' );
26 like($@, $ex_regex);
27
28 # Now lets rethrow via exception_action
29 $schema->exception_action(sub { die @_ });
30 eval { throwex };
31 like($@, $ex_regex);
32
33 # Now lets suppress the error
34 $schema->exception_action(sub { 1 });
35 eval { throwex };
36 ok(!$@, "Suppress exception");
37
38 # Now lets fall through and let croak take back over
39 $schema->exception_action(sub { return });
40 eval { throwex };
41 like($@, $ex_regex);
42
43 # Whacky useless exception class
44 {
45     package DBICTest::Exception;
46     use overload '""' => \&stringify, fallback => 1;
47     sub new {
48         my $class = shift;
49         bless { msg => shift }, $class;
50     }
51     sub throw {
52         my $self = shift;
53         die $self if ref $self eq __PACKAGE__;
54         die $self->new(shift);
55     }
56     sub stringify {
57         "DBICTest::Exception is handling this: " . shift->{msg};
58     }
59 }
60
61 # Try the exception class
62 $schema->exception_action(sub { DBICTest::Exception->throw(@_) });
63 eval { throwex };
64 like($@, qr/DBICTest::Exception is handling this: $ex_regex/);
65
66 # While we're at it, lets throw a custom exception through Storage::DBI
67 eval { $schema->storage->throw_exception('floob') };
68 like($@, qr/DBICTest::Exception is handling this: floob/);
69
70
71 done_testing;