Contributed by turumkhan
on Jun 08, 2001 at 00:17 UTC
Q&A
> programs and processes
Description: 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 Answer: how do i trap the error generated by perl contributed by bikeNomad 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!");
| Answer: how do i trap the error generated by perl contributed by arturo 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 $@;
| Answer: how do i trap the error generated by perl contributed by LuTze 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";
|
Please (register and) log in if you wish to add an answer
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Outside of code tags, you may need to use entities for some characters:
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
|