Beefy Boxes and Bandwidth Generously Provided by pair Networks Bob
There's more than one way to do things
 
PerlMonks  

how do i trap the error generated by perl

by turumkhan (Novice)
on Jun 07, 2001 at 20:17 UTC ( [id://86721]=perlquestion: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.

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 07, 2001 at 20: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 07, 2001 at 21: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 12: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?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://86721]
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.