LinuxQuestions.org
Go Job Hunting at the LQ Job Marketplace
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices

Reply
 
Search this Thread
Old 07-22-2008, 02:32 PM   #1
2007fld
Member
 
Registered: Mar 2007
Distribution: FD4,6
Posts: 52

Rep: Reputation: 15
Perl error message processing


I'm writing a Perl script to connect to a database:

Quote:
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'?
 
Old 07-22-2008, 03:21 PM   #2
TB0ne
Guru
 
Registered: Jul 2003
Location: Birmingham, Alabama
Distribution: SuSE, RedHat, Slack,CentOS
Posts: 14,771

Rep: Reputation: 2614Reputation: 2614Reputation: 2614Reputation: 2614Reputation: 2614Reputation: 2614Reputation: 2614Reputation: 2614Reputation: 2614Reputation: 2614Reputation: 2614
Quote:
Originally Posted by 2007fld View Post
I'm writing a Perl script to connect to a database:



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'?
Check out http://www.perlmonks.com, they may be able to give lots more info.

Have you tried doing something like:

Code:
|| die (system "echo \"Mysql is dead!\" | mailx -s \"MySQL dead on myserver\" user@domain.com");
or

Code:
|| die {Database connection not made: $DBI::errstr";
(system "echo \"Mysql is dead!\" | mailx -s \"MySQL dead on myserver\" user@domain.com"); }
Not checked at all, for syntax or anything else, so I have no idea if it'll work. Good luck
 
Old 07-22-2008, 07:17 PM   #3
chrism01
Guru
 
Registered: Aug 2004
Location: Sydney
Distribution: Centos 6.5, Centos 5.10
Posts: 16,289

Rep: Reputation: 2034Reputation: 2034Reputation: 2034Reputation: 2034Reputation: 2034Reputation: 2034Reputation: 2034Reputation: 2034Reputation: 2034Reputation: 2034Reputation: 2034
Here's my custom routine:

Code:
#******************************************************************************
#
# Function      : send_email
#
# Description   : Send an email warning for errors
#                 Can be called from exit_with_error(), so don't call
#                 exit_with_error(), otherwise infinite loop.
#
# Params        : $_[0]     error msg 
#
# Returns       : none
#
#******************************************************************************
sub send_email
{
    my (
        $error_msg,         # input error msg
        $hostname,          # name of this box for sending
        $prog_full_name,    # prog path + name
        $contact_email,     # contact email address
        $mailer,            # mailer object
        $sender,            # sender of email as specified in cfg file
        $subject,           # subject line in email
        $body_text          # actual email msg text
        );

    # Assign input params
    $error_msg = $_[0];

    # Get hostname anyway we can using Sys::Hostname;
    # tries syscall(SYS_gethostname), `hostname`, `uname -n`
    $hostname = Sys::Hostname::hostname();

    # Get program full path name
    $prog_full_name = cwd()."/${0}";

    # Set the fields required by Mailer...
    $contact_email = $cfg::params{'ADMIN_EMAIL'};
    $sender = "$prog_full_name";
    $subject = "$prog_full_name: Error trapped";
    $body_text = "This is an automated message:\n\n".
                 "$error_msg\n\n".
                 "Regards,\n$prog_full_name at $hostname\n\n";

    # ... and send it
    $mailer = Mail::Mailer->new();
    $mailer->open({ From    => $sender,
                    To      => $contact_email,
                    Subject => $subject,
                    }) or print "Can't open Mailer for send: $!\n";
    print $mailer $body_text;
    close($mailer) or print "Can't close Mailer: $!\n";
}
You'll need
Code:
use Mail::Mailer;       # Access sendmail
use Sys::Hostname;      # Used to insert hostname in emails
use Cwd;                # Get current full dir for error msgs
Also, you're using wrong type of 'or':
'||' is for inside if( $a || $b) constructs. For 'or die' eg file/db open, use 'or' eg
Code:
$file="test.txt";
open( TXT_FILE, "<$file" ) or
            die "Can't open txt file: $file: $!\n";
Its a precedence issue.
http://perldoc.perl.org/functions/open.html
Code:
#******************************************************************************
#
# Function      : db_connect
#
# Description   : Connect to the Database
#
# Params        : none
#
# Returns       : none
#
#******************************************************************************
sub db_connect
{
    my (
        $dsn,   # data source name
        );

    # Create data source string and connect ...
    $dsn = "DBI:mysql:".
           "database=".$cfg::params{'DB_NAME'}.";".
           "host=".$cfg::params{'DB_HOST'}.";".
           "port=".$cfg::params{'DB_PORT'};
    $cfg::dbh = DBI->connect( $dsn, $cfg::params{'DB_USER'},
                                $cfg::params{'DB_PASSWD'},
                                {RaiseError => 0, PrintError => 0,
                                 AutoCommit => 0} );

    if( $DBI::errstr)
    {
        exit_with_error($DBI::errstr);
    }

}
custom exit routines
Code:
#******************************************************************************
#
# Function      : exit_with_success
#
# Description   : Controlled exit with Success status
#
# Params        : none
#
# Returns       : none
#
#******************************************************************************
sub exit_with_success
{
    print "$0 exiting OK.\n";
    exit(0);
}

#******************************************************************************
#
# Function      : exit_with_error
#
# Description   : Controlled exit with Error status and error msg
#
# Params        : $_[0]     error msg from calling fn
#
# Returns       : none
#
#******************************************************************************
sub exit_with_error
{
    my (
        $error_msg  # error msg from caller
        );

    # Grab error msg, print/log it, email it, 
    # rollback DB, exit with error status
    $error_msg = $_[0];
    print "$0 exiting with error. Msg was:\n$error_msg\n";
    send_email("$0 exiting with error. Msg was:\n$error_msg\n");
    db_rollback_txn();

    exit(1);
}
Enjoy

Last edited by chrism01; 07-22-2008 at 07:21 PM.
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Perl use prima; Prima(perl) (image processing software))error knockout_artist Linux - Software 2 09-11-2007 10:13 PM
Strange Repeating Error message in /var/log/message lucktsm Linux - Security 2 10-27-2006 08:29 AM
nim processing error opeyrega AIX 1 09-11-2006 06:26 AM
Web Page Retrieval & Processing with PERL BBQ_Matt Programming 3 10-25-2003 09:20 AM
Simple Perl prog. getting Error 500 message. XxAndyxX Programming 1 07-06-2003 11:25 AM


All times are GMT -5. The time now is 11:30 AM.

Main Menu
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration