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

I have a program that uses DBI to perform sql tasks into an oracle database. I want to quit the program if an error is returned from the sql command. however, I want the error to go to STDERR and I want to print a custom message to STDOUT before dieing.
my $dbh = DBI->connect('dbi:Oracle:miemsdb', 'ipse', 'ipse', {AutoComm +it => 0}) || die "RC-E\n"; open (STDERR, ">ERR/ERRORS_${myPID}"); ########################### my $DirChk = $dbh->prepare($sqlChkDir) || die "RC-E\n"; $DirChk->execute($DirName) || die "RC-E\n";
With this code I do get the oracle error and the "RC-E" into the ERRORS_$ file. But I want to send the RC-E to stdout.

Replies are listed 'Best First'.
Re: die send to stdout & stderr
by pc88mxer (Vicar) on May 02, 2008 at 21:12 UTC
    Adding RaiseError => 1 to the connect call might also work for you in which case you won't have to add || die ... after each call.

    You also have the ability to change the behavior of die by installing a custom $SIG{__DIE__} handler:

    $SIG{__DIE__} = sub { print STDERR @_; print STDOUT ...; # whatever you want exit(1); };
    Just throwing some out some ideas/options.

    Update: if RC-E represents some sort of context or scope that you want to report via STDOUT, you could use a localize global variable to remember what the current context is.

    our $::error_context; { local $::error_context = "RC-E"; $dbh->prepare(...); # dbh call in the RC-E context { local $::error_context = "RC-F"; $dbh->whatever(...); # dbh call in the RC-F context } # back to context "RC-E" ... }
    Then the SIG{__DIE__} handler can determine the context by inspecting $::error_context.
      Thank You for the info. I like the idea of creating a custom die handler. I will try it.
Re: die send to stdout & stderr
by Corion (Patriarch) on May 02, 2008 at 21:08 UTC

    Then don't use die. die always outputs to STDERR (the error channel). You could write a subroutine die_STDOUT like this:

    sub die_STDOUT { print STDOUT "@_\n"; exit 1; };
Re: die send to stdout & stderr
by runrig (Abbot) on May 02, 2008 at 21:56 UTC
    If you just want to catch DBI errors, there is a HandleError attribute for DBI. Alternatively you can set RaiseError to true, and wrap your DBI calls in an eval block, then handle the error after the block.