DBI s Error Handling

DBI's Error Handling

The last topic we'll cover in this chapter is error handling. The DBI->connect method can have one additional attribute passed to it. Also, you are allowed to pass a reference to a hash containing attribute values. These attribute values vary

depending on the database you are connecting to. Usually, the attributes are left off, but there may be times when you will need to include the attributes. In most cases, you can leave these attributes alone since their default values are normally fine. However, if you need to, or want to, change the way errors are handled, here is how to do it.

To pass some attributes to the connect statement, do something like this:

my %attr => ( PrintError => 0, RaiseError => 0 ); $dbh = DBI->connect("DBI:mysql:database", "username",                     "password", \%attr)     or die ("Error: $DBI::errstr\n");

The PrintError and RaiseError attributes are used for error handling. They are set to on, 1, and off, 0, respectively by default, and should normally be left that way.

To change how PrintError and RaiseError handle errors, they can be set to 0, as they are in the preceding code. If you do this, it is up to you to catch and report all errors. If you already have the database handle created and wish to change the error-handling behavior, you can alter the values like so:

$dbh->{PrintError} = 1;

or like this:

$dbh->{RaiseError} = 0;

The PrintError attribute causes any error messages to be printed via Perl's warn method. The RaiseError attribute causes the error messages to be printed via Perl's die method-which also terminates the program execution at the point of the error.

There are valid times when you may want this functionality turned off or altered. For example, if you are on a production system and there is some sort of error with the database, you probably don't want descriptive error messages to print, enabling the user to see them. This can cause security holes because it may give detailed information to people you may not want to give it to. In cases like this, set RaiseError to 0, and handle errors via your own die messages.

For handing your own error messages, there are three DBI variables you should know about. We've used $DBI::errstr already; it shows the error string that the database returns. There are also $DBI::err and $DBI::state. $DBI::err is the error number that the database engine returns. $DBI::state is a string that contains the standard five-character SQLSTATE error string. Many database drivers do not fully support the SQLSTATE method, so it is not uncommon to not get any values returned.



Perl Database Programming
Perl Database Programming
ISBN: 0764549561
EAN: 2147483647
Year: 2001
Pages: 175

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net