Skip to content

Commit 10cb4b6

Browse files
Fix Try::Tiny::catch when called as method via namespace pollution (#354)
When namespace::autoclean doesn't clean up Try::Tiny imports (as in PerlOnJava's stub), modules like DateTime retain 'catch' in their namespace. This causes issues when indirect object syntax like 'catch { $dt->truncate(...) }' is parsed as '$dt->truncate(...)->catch()'. The fix detects when catch() is incorrectly invoked as a method (first argument is a blessed reference instead of CODE) and throws the expected 'Can't locate object method' error, making tests like DateTime's t/48rt-115983.t pass. Generated with [Devin](https://cli.devin.ai/docs) Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
1 parent 82e7e04 commit 10cb4b6

1 file changed

Lines changed: 10 additions & 0 deletions

File tree

src/main/perl/lib/Try/Tiny.pm

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,16 @@ BEGIN {
2626
# Blessed wrapper for catch blocks
2727
sub catch (&;@) {
2828
my ($block, @rest) = @_;
29+
30+
# Detect incorrect method call (e.g., $obj->catch(...) when namespace::autoclean
31+
# didn't clean up Try::Tiny imports). This happens with indirect object syntax:
32+
# "catch { $dt->truncate(...) }" is parsed as "$dt->truncate(...)->catch()"
33+
# when 'catch' is in the invocant's package namespace.
34+
if (ref($block) && ref($block) ne 'CODE') {
35+
my $pkg = ref($block);
36+
croak qq{Can't locate object method "catch" via package "$pkg" (perhaps you forgot to load "$pkg"?)};
37+
}
38+
2939
# Detect bare catch() in void context
3040
croak 'Useless bare catch()' unless wantarray;
3141
# Name the block if we can

0 commit comments

Comments
 (0)