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

I'm writing a Perl script to connect to a database:
my $dbh = DBI->connect('DBI:Oracle:host=**,sid=***', 'usrname', 'passwd', { RaiseError => 1, AutoCommit => 0 } ) || die "Database connection not made:$DBI::errstr";
What I want is, when the database connection is NOT set up, the script should email me to let me know. But since the die command is there to terminate the program right after the unsuccessful connection, how do I add the command, like 'sendmail'?

Replies are listed 'Best First'.
Re: how to deal with error message
by Lawliet (Curate) on Jul 22, 2008 at 19:51 UTC

    Instead of having it die, simply have it call a subroutine that sends you the email, then exit.

    my $dbh = DBI->connect('DBI:Oracle:host=**,sid=***', 'usrname', 'passw +d', { RaiseError => 1, AutoCommit => 0 } ) or sendmail(); sub sendmail { ... #Send mail here die; }

    Update: Or, instead of having the die command in your subroutine (which may be troublesome if you plan to call the subroutine more than once) you can use or sendmail() and die; rather than just sendmail();

    <(^.^-<) <(-^.^<) <(-^.^-)> (>^.^-)> (>-^.^)>
      Update: Or, instead of having the die command in your subroutine (which may be troublesome if you plan to call the subroutine more than once) you can use or sendmail() and die; rather than just sendmail();

      DBI->connect(...) or sendmail() and die; would mean to die whenever the connection is successful ;-)

      I guess you meant DBI->connect(...) or do { sendmail(); die; };. :)

      --
      altblue.

        Oh, would it? Thanks for correction; that is what I meant.

        <(^.^-<) <(-^.^<) <(-^.^-)> (>^.^-)> (>-^.^)>
        ...or why not,

        sendmail(), die unless DBI->connect(...)

        At last, a user level that overstates my experience :-))
Re: how to deal with error message
by moritz (Cardinal) on Jul 22, 2008 at 19:52 UTC
    Write a sub that does what you want:
    sub send_mail { my $msg = shift; # send mail here... warn $msg; exit; }
    And then call it instead of die:
    my $dbh = DBI->connect('DBI:Oracle:host=**,sid=***', 'usrname', 'passw +d', { RaiseError => 1, AutoCommit => 0 } ) || send_mail "Database connection not made:$DBI::errstr";
Re: how to deal with error message
by leocharre (Priest) on Jul 23, 2008 at 02:48 UTC

    If you have things like this on your network, you should seriously consider nagios.

    Imagine you want to receive an email alert if there are 5 files in directory x, but if there are 20 or more, send a message to your cell phone instead. Right.

    There's info out there for writing plug ins for nagios, so you can customize what happens.