Hello Monks,
Occasionally my users get errors when they are trying to use my application when database connections are exhausted. It happens infrequently enough that I want to trap the error and try to open the DB again. For some reason I get the old "Internal Server Error". Inside the Apache error log I get the appropriate error - Can't connect to MySQL server on <ipaddress>:<port>. Before you see the code, I have two points. First, if on the DBI->connect I put
DBI->connect(....) || fatal(error message)
the fatal piece is invoked, with the code below, I get the "Internal Server Error". Second, fatal is a custom error routine that emails me and puts a nice message up for the user. I only want that error to show up after I have tried a few times. Here is the code:
sub openDB {
my ($database, $user_id, $password) = ();
open( CFG, $db_cfg ) or fatal("Cannot open databse config file.");
($database, $user_id, $password, $pwkey) = split( ',', <CFG>);
$done = 0;
$num_tries = 0;
while (!$done) {
$num_tries += 1;
# If we exceeded the custom amount of attempts call error rou
+tine
if ($num_tries > 4) {
fatal (" Could not open database: $DBI::errstr");
$done = 1;
}
else {
# Make the database connection
eval {
$dbh = DBI->connect("DBI:mysql:$database:<ipaddress:po
+rt>", $user_id, $password);
}
# If there is an error try again
if ($@) {
next;
}
# No error drop out of loop
else {
$done = 1;
}
}
}
}
Thanks in advance for your suggestions
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
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, details, 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, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
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.