Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error handling on DBI->connect

Tags:

perl

dbi

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.

like image 966
Hozy Avatar asked Jul 11 '11 11:07

Hozy


People also ask

What is DBI Errstr?

Since scripts don't use the internal driver handles, the $DBI::errstr variable provides a very simple and effective way to get the error message from a connect() failure. In summary, for most applications, automatic error checking using RaiseError and/or PrintError is recommended.

What is Perl DBI in MySQL?

Perl/DBI modules. DBI is a database-independent interface for the Perl programming language. DBD::mysql is the driver for connecting to MySQL database servers with DBI. DBI is the basic abstraction layer for working with databases in Perl.

What is DBI module in Perl used for?

The DBI is a database access module for the Perl programming language. It provides a set of methods, variables, and conventions that provide a consistent database interface, independent of the actual database being used.


1 Answers

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.

like image 160
Chas. Owens Avatar answered Oct 14 '22 16:10

Chas. Owens