Search code examples
perllwpdiexml-simple

Is it possible to catch die messages that happen inside another perl module?


I have a SOAP client written in Perl using LWP package for the HTTPS transport and XML::Simple for the parsing of the XML payloads. From time to time the call to XMLin fails with a die() and then my script dies and has to be restarted by a monitoring program that I have written to detect this. This is really not desirable, and so I was wondering if Perl has any facility like the C++ exception handling mechanism where I can catch the die message, ignore it report the error and let my script continue just as if an error occurred? I have read a number of Perl books and looked for this but I have not managed to find something. This is killing my application but I dont want to write my own XML parsing code unless I absolutely have to.


Solution

  • Yes; the basic mechanism for doing this would be an eval:

    sub a { die "BAD"; }
    eval { a(); }
    print "Survived an exception $@";
    

    However, there are reasons why you should use more high-level constructs (which are nevertheless constructed on top of this), like Try::Tiny et al. (see the links at the bottom of its documentation).