Database Reference
In-Depth Information
if
(
$@
)
{
print
"An error occurred: $@\n"
;
}
This
eval
technique is commonly used to perform transactions (see
Recipe 17.4
).
Using
RaiseError
in combination with
eval
differs from using
RaiseError
alone:
• Errors terminate only the
eval
block, not the entire script.
• Any error terminates the
eval
block, whereas
RaiseError
applies only to DBI-
related errors.
When you use
eval
with
RaiseError
enabled, disable
PrintError
. Otherwise, in some
versions of DBI, an error may simply cause
warn()
to be called without terminating the
eval
block as you expect.
In addition to using the error-handling attributes
PrintError
and
RaiseError
, lots of
information about your script's execution is available using DBI's tracing mechanism.
Invoke the
trace()
method with an argument indicating the trace level. Levels 1 to 9
enable tracing with increasingly more verbose output, and level 0 disables tracing:
DBI
->
trace
(
1
);
# enable tracing, minimal output
DBI
->
trace
(
3
);
# elevate trace level
DBI
->
trace
(
0
);
# disable tracing
Individual database and statement handles also have
trace()
methods, so you can lo‐
calize tracing to a single handle if you want.
Trace output normally goes to your terminal (or, in the case of a web script, to the web
server's error log). To write trace output to a specific file, provide a second argument
that indicates the filename:
DBI
->
trace
(
1
,
"/tmp/trace.out"
);
If the trace file already exists, its contents are not cleared first; trace output is appended
to the end. Beware of turning on a file trace while developing a script, but forgetting to
disable the trace when you put the script into production. You'll eventually find to your
chagrin that the trace file has become quite large. Or worse, a filesystem will fill up, and
you'll have no idea why!
Ruby
Ruby signals errors by raising exceptions and Ruby programs handle errors by catching
exceptions in a
rescue
clause of a
begin
block. Ruby DBI methods raise exceptions
when they fail and provide error information by means of a
DBI::DatabaseError
object.
To get the MySQL error number, error message, and SQLSTATE value, access the
err
,
errstr
, and
state
methods of this object. The following example shows how to trap
exceptions and access error information in a DBI script: