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