Hozy
Hozy

Reputation: 265

Error handling on DBI->connect

Besides handling error using standard code die "Unable to connect: $DBI::errstr\n" is it possible to write a custom code like below?

Standard:

$dbstore = DBI->connect($dsn, $user, $pw,
    {ora_session_mode => $mode, PrintError => 0, RaiseError => 0, AutoCommit => 0}) 
    or die "Unable to connect: $DBI::errstr\n";

Custom:

$dbstore = DBI->connect($dsn, $user, $pw,
    {ora_session_mode => $mode, PrintError => 0, RaiseError => 0, AutoCommit => 0});

if (!$dbstore)
{
    CUSTOM_LOG_HANDLER("Could not connect to database: $DBI::errstr");
    return;
}

Sample Standard Code:

#!/usr/bin/perl

# PERL MODULES WE WILL BE USING
use DBI;
use DBD::mysql;

# HTTP HEADER
print "Content-type: text/html \n\n";

# CONFIG VARIABLES
$platform = "mysql";
$database = "store";
$host = "localhost";
$port = "3306";
$tablename = "inventory";
$user = "username";
$pw = "password";

#DATA SOURCE NAME
$dsn = "dbi:mysql:$database:localhost:3306";

# PERL DBI CONNECT (RENAMED HANDLE)
$dbstore = DBI->connect($dsn, $user, $pw) or die "Unable to connect: $DBI::errstr\n";

Thanks for you time.

Upvotes: 6

Views: 21581

Answers (1)

Chas. Owens
Chas. Owens

Reputation: 64919

You can always use a custom error handler with the DBI:

#!/usr/bin/perl

use strict;
use warnings;

use DBI;

sub handle_error {
    my $message = shift;
    #write error message wherever you want
    print "the message is '$message'\n";
    exit; #stop the program
}

my $dbh = DBI->connect(
    "dbi:SQLite:foo",
    "user",
    "pass",
    {
        PrintError  => 0,
        HandleError => \&handle_error,
    }
) or handle_error(DBI->errstr);

my $sth = $dbh->prepare("select * from doesntexist");

That said, you should be logging errors, and for a web application, the web server's logs makes sense. If you are worried about the amount of noise in your web logs, you should concentrate on fixing the errors, not making the logs less noisy by removing sources of information.

Upvotes: 18

Related Questions