Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

how do i trap the error generated by perl

by turumkhan (Novice)
on Jun 08, 2001 at 00:17 UTC ( #86721=perlquestion: print w/replies, xml ) Need Help??

turumkhan has asked for the wisdom of the Perl Monks concerning the following question: (programs and processes)

How do i trap the error gnerated by perl and make it my custom made error messages. This would be of great help to me. if any one can do that. thanks - turumkhan

Originally posted as a Categorized Question.

  • Comment on how do i trap the error generated by perl

Replies are listed 'Best First'.
Re: how do i trap the error generated by perl
by bikeNomad (Priest) on Jun 08, 2001 at 00:46 UTC
    You need to look at the discussions of die() and warn() and the %SIG hash. You can set up your own handlers for errors (via die) using $SIG{__DIE__} = sub { ... } and for warnings (via warn) using $SIG{__WARN__} = sub { ... }. See the perlvar and perlfunc manpages. You can also run code that you think might die inside an eval { } construction and keep your program from dying.
    #!/usr/bin/perl -w use strict; $SIG{__DIE__} = sub { die("My error: ", @_); }; $SIG{__WARN__} = sub { warn("My warning: ", @_); }; warn("some warning"); die("aarggh!");
Re: how do i trap the error generated by perl
by arturo (Vicar) on Jun 08, 2001 at 01:25 UTC

    Using eval {}; and $@ (which, if set, contains the error message that would otherwise be fatal -- see perldoc perlvar) will allow you to catch most errors:

    eval { #code you want to catch errors from }; custom_error_handler($@) if $@;
Re: how do i trap the error generated by perl
by LuTze (Initiate) on Feb 09, 2010 at 17:15 UTC

    bikeNomad's answer is correct, with an addendum.

    Using signals is not always straightforward. Signals are handled asynchronously and can interrupt each other. If you are, for example, redirecting those messages to a file, one signal might come in while the previous one is still processing, and stop it from going any further. You could loose some warnings that way, especially if they are being emitted from a tight loop and the handler is slow to execute.

    In this case, it may be easier to redirect STDERR, which can be done with something like:

    my $old_stderr = STDERR; open STDERR, ">mylogfile.log";

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://86721]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (5)
As of 2021-04-18 21:43 GMT
Find Nodes?
    Voting Booth?

    No recent polls found