I use
Error in my personal scripty-doos at work (it's actually a bunch of modules for my personal consumption) and it works really well. You have to create a bunch of Error classes that will describe the type of error you are trapping on. This is because
Error deals with the class of the error and makes decisions based on that.
Here's what I do with DBI (for instance}:
# Within some connect_to_db() function ...
my $dbh = try {
DBI->connect(
$conn_string,
$props{USER},
$props{PWD},
{
PrintError => 0,
RaiseError => 1,
},
)
} otherwise {
throw Error::Database -text => (
$DBI::errstr
|| $@
|| "Unknown Error: '$conn_string'"
);
};
$dbh->{HandleError} = sub { throw Error::Database -text => $DBI::er
+rstr };
return $dbh;
}
# Now, any DB action I take that would ordinarily return undef
# will now throw an Error::Database. As long as all my DB
# activity is within a try-catch area, I'm fine. :-)
# Within another section, I have:
my ($dbh, $fh);
try
{
my ($properties, $datafile) = Parameter::Validate(@ARGV, 2);
$dbh = Database::Connect(File::ReadProperties($properties));
my %db_values = Retrieve_DB_Values($dbh);
$fh = File::Open(
$datafile,
mode => 'w',
);
# Do more stuff here
}
catch Error::Simple with
{
my ($err, $recover) = @_;
throw Error::Unknown -text => $err->text;
}
catch Error with
{
my ($err, $recover) = @_;
die $err->text . $/;
}
otherwise
{
throw Error::Unknown -text => $@;
}
finally
{
Database::Disconnect($dbh);
File::Close($fh);
};
Note that I have wrapped around
DBI->connect and
IO::File->new, in order to provide consistent error handling.
------
We are the carpenters and bricklayers of the Information Age.
Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.
Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
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, 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, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Outside of code tags, you may need to use entities for some characters:
| |
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.