3dkiwi has asked for the wisdom of the Perl Monks concerning the following question:

Dear deities,
I am writing an RSS aggregator and have chosen the XML::RSS parser to read the feeds. I have it all working except when there is an error in the feeds XML file. The documentation for XML::RSS states that a die is produced when there is an error in the parsed XML but I would like to trap this error and not die. I would then do a next to continue onto the next feed, maybe generating my own error message etc.
I am not sure how to wrap the XML::RSS in some form of error checking...
Example pseudo code:
!/usr/bin/perl -T $| = 1; use strict; use warnings; use XML::RSS; use LWP::Simple; use POSIX qw(strftime); my $there_is_a_feed_to_be_read = "true"; my $url_to_read = "http://xxx.xml"; my $url2parse; my $rss; while ( $there_is_a_feed_to_be_read ) { $rss = new XML::RSS; $url2parse = get( $url_to_read ); die "Could not retrieve $url_to_read" unless $url2parse; # all works up to this point but if there is an error in the # XML being read the next command chokes. # What I am looking for is some sort of wrapper to do a next # if there is a problem so we just step over the faulty feed $rss->parse($url2parse); # deal with the returned XML information here # . # . # . }
Not wanting to name names but at the present time the following feed has a raw & symbol in the text that the parser is tripping over.
http://developer.apple.com/rss/adcheadlines.rss
Many thanks in advance
3d

Replies are listed 'Best First'.
Re: Trapping Errors from XML::RSS
by kyle (Abbot) on Jun 19, 2007 at 03:27 UTC

    You want to use the block form of eval. Here's the quick and dirty:

    next if ( ! eval { $rss->parse($url2parse); 1 } );

    A slightly more involved example:

    use English qw( -no_match_vars ); eval { $rss->parse($url2parse); }; if ( $EVAL_ERROR ) { my $err = $EVAL_ERROR; if ( $err =~ /bad feed or whatever/ ) { next; } else { # some error you weren't expecting die $err; # rethrow it } }

    If you don't use English, $EVAL_ERROR is known as $@. See perlvar.

      Kyle
      Your quick and dirty example hit the spot. I will pad it out a bit for my application. And again thanks to you and Zaxo for the tips.
      3d
      PS if you want to see my other coding attempts check out http://www.pyenet.co.nz/pro-pro.html
      Kyle
      Sounds like the solution. Many thanks for the quick response. Will give it a try and let you know the results.
      Again thanks
      3d
Re: Trapping Errors from XML::RSS
by Zaxo (Archbishop) on Jun 19, 2007 at 03:27 UTC

    When you want to trap die-ing code, eval it. Eval will return undefined if the code died and $@ will have the error message.

    Update: kyle++ pointed out a major thinko, naming the wrong function, repaired.

    After Compline,
    Zaxo