shlomif / perl-XML-LibXML

The XML-LibXML CPAN Distribution for Processing XML using the libxml2 library
https://metacpan.org/release/XML-LibXML
Other
17 stars 35 forks source link

Missing error handling for nextPatternMatch method #46

Open ikorchynskyi opened 4 years ago

ikorchynskyi commented 4 years ago

It seems that nextPatternMatch does not die on error like e.g. read:

#!/usr/bin/env perl

use strict;
use warnings;

use XML::LibXML;
use XML::LibXML::Reader qw(:types);

my $bad_xml = <<'__TEXT__';
    <root>
        <x>foo</u>
        <x>bar</x>
    </root>
__TEXT__

my $pattern = XML::LibXML::Pattern->new(
    '/root/x',
);

{
    print "[nextPatternMatch]\n";
    my $reader = XML::LibXML::Reader->new(
        string => $bad_xml,
        URI => 'nextPatternMatch.xml'
    );
    eval {
        while ( $reader->nextPatternMatch($pattern) == 1 ) {
            next unless $reader->nodeType == XML_READER_TYPE_ELEMENT;
            printf "innerXml: [%s]\n", $reader->readInnerXml;
        }
        $reader->finish;
        print "finish\n";
    };
    print "Eval error: [$@]" if $@;
}

{
    print "[matchesPattern]\n";
    my $reader = XML::LibXML::Reader->new(
        string => $bad_xml,
        URI => 'matchesPattern.xml'
    );
    eval {
        while ( $reader->read == 1 ) {
            next unless $reader->matchesPattern($pattern);
            next unless $reader->nodeType == XML_READER_TYPE_ELEMENT;
            printf "innerXml: [%s]\n", $reader->readInnerXml;
        }
        $reader->finish;
        print "finish\n";
    };
    print "Eval error: [$@]" if $@;
}

Output:

[nextPatternMatch]
nextPatternMatch.xml:2: parser error : Opening and ending tag mismatch: x line 2 and u
        <x>foo</u>
                  ^
finish
[matchesPattern]
Eval error: [matchesPattern.xml:2: parser error : Opening and ending tag mismatch: x line 2 and u
        <x>foo</u>
                  ^
]

As you can see, read seems to produce error while nextPatternMatch just warn in STDERR. And it seems that there is no way to obtain error message in normal way (except STDERR capture).