The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

OpenPlugin::Exception - Base class for exceptions in OpenPlugin

SYNOPSIS

 # Throw an exception

 $OP->exception->throw("An exception has occurred");

 # Throw an exception, and log the message using the Log Plugin

 $OP->exception->log_throw("An exception has occurred");

 # Catch an exception, get more info on it with creation_location()

 eval { $OP->session->save( $session ) };
 if ( $@ ) {
    print "Error: $@", $@->creation_location, "\n";
 }

 # Or, get a stack trace

 eval { $OP->session->save( $session ) };
 if ( $@ ) {
    print "Error: $@",
          "Stack trace: ", $@->trace->as_string, "\n";
 }

 # Get all exceptions (including from subclasses that don't override
 # throw()) since the stack was last cleared

 my @errors = $OP->exception->get_stack;
 print "Errors found:\n";
 foreach my $e ( @errors ) {
    print "ERROR: ", $e->creation_location, "\n";
 }

 # As a developer of a module which uses OpenPlugin

 my $rv = eval { $dbh->do( $sql ) };
 if ( $@ ) {
     $@->throw( "There was an error! $@" );
 }

 # Throw an exception that subclasses OpenPlugin::Exception with extra
 # fields (Assumes creation of OpenPlugin::Exception::DBI)

 my $rv = eval { $dbh->do( $sql ) };
 if ( $@ ) {
     $OP->exception('DBI')->throw( $@, { sql    => $sql,
                                         action => 'do' } );
 }

 # Catch an exception, do some cleanup then rethrow it

 my $rv = eval { $OP->session->fetch( $session_id ) };
 if ( $@ ) {
     my $exception = $@;
     $OP->datasource->disconnect('Database_DataSource');
     $OP->datasource->disconnect('LDAP_DataSource');
     $OP->exception->throw( $exception );
 }

DESCRIPTION

This class is the base for all exceptions in OpenPlugin. An exception is generally used to indicate some sort of error condition rather than a situation that might normally be encountered. For instance, you would not throw an exception if you tried to fetch() a record not in a datastore. But you would throw an exception if the query failed because the database schema was changed and the SQL statement referred to removed fields.

You can easily create new classes of exceptions if you like, see SUBCLASSING below.

METHODS

throw( $message, [ \%params ] )

This is the main action method and often the only one you will use. It creates a new exception object and calls die with the object. Before calling die with it it first does the following:

1. We check \%params for any parameters matching fieldnames returned by get_fields(), and if found set the field in the object to the parameter.
2. Fill the object with the relevant calling information: package, filename, line, method.
3. Set the trace property of the object to a Devel::StackTrace object.
4. Call initialize() so that subclasses can do any object initialization/tracking they need to do. (See SUBCLASSING below.)
5. Track the object in our internal stack.

log_throw( $message, [ \%params ] )

Same as throw, except that it logs the message first using the Log plugin. Logging occurs at the fatal level.

get_stack()

Returns a list of exceptions that had been put on the stack. This can be particularly useful when there are multiple errors thrown during the execution of your program, and you want to get information regarding each one.

 my @errors = $OP->exception->get_stack;
 print "Errors found:\n";
 foreach my $e ( @errors ) {
    print "ERROR: ", $e->creation_location, "\n";
 }

Instead of $e-creation_location>, which gives you several pieces of information about each error, you can get individual pieces of information using the following individual methods:

 print $e->message;
 print $e->package;
 print $e->filename;
 print $e->line;
 print $e->method;
 print $e->trace;

get_fields()

Returns a list of property names used for this class. If a subclass wants to add properties to the base exception object, the common idiom is:

 my @FIELDS = qw( this that );
 sub get_fields { return ( $_[0]->SUPER::get_fields(), @FIELDS ) }

So that all fields are represented.

creation_location

Returns a string with information about where the exception was thrown. It looks like (all on one line):

 Created in [%package%] in method [%method%];
 at file [%filename%] at line [%line%]

PROPERTIES

The following properties are default properties of an OpenPlugin::Exception object. Don't forget that one can add to this property list by subclassing this module. These properties can be accessed using:

  $exception_object->state->{ $property_name };

message

This is the message the exception is created with -- there should be one with every exception. (It is bad form to throw an exception with no message.)

package

The package the exception was thrown from.

filename

The file the exception was thrown from.

line

The line number in filename the exception was thrown from.

method

The subroutine the exception was thrown from.

trace

Returns a Devel::StackTrace object, which had been created at the point where the exception was thrown.

 $@->state->{ trace }->as_string;

SUBCLASSING

It is very easy to create your own OpenPlugin::Exception or application errors:

 package My::Custom::Exception;

 use strict;
 use base qw( OpenPlugin::Exception );

Easy! A subclass will often allow developers to pass in additional parameters:

 package My::Custom::Exception;

 use strict;
 use base qw( OpenPlugin::Exception );
 my @FIELDS = qw( this that );

 sub get_fields { return ( $_[0]->SUPER::get_fields(), @FIELDS ) }

And now your custom exception can take extra parameters:

 $self->exception('name')->throw( $@, { this => 'bermuda shorts',
                                        that => 'teva sandals'    });

The name parameter being passed into the exception plugin above is the driver name given to your subclass. Available drivers are defined in the OpenPlugin-drivermap.conf file, and enabled in the OpenPlugin.conf file.

If you want to do extra initialization, data checking or whatnot, just create a method initialize(). It gets called just before the die is called in throw(). Example:

 package My::Custom::Exception;

 # ... as above

 my $COUNT = 0;
 sub initialize {
     my ( $self, $params ) = @_;
     $COUNT++;
     if ( $COUNT > 5 ) {
         $self->state->{ message } (
               $self->state->{ message } .
                   "-- More than five errors?! ($COUNT) Whattsamatta?" );
     }
 }

BUGS

None known.

TO DO

Nothing known.

NOTES

This module is very similar to SPOPS::Exception distributed with SPOPS by Chris Winters. Much of the code was copied and pasted into here, after the usual tweaking, of course :-) A big thanks to Chris for all his help.

SEE ALSO

OpenPlugin

Devel::StackTrace

SPOPS::Exception

Exception::Class for lots of good ideas.

Copyright (c) 2001-2003 Eric Andreychek. All rights reserved.

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

AUTHORS

Eric Andreychek <eric@openthought.net>

Chris Winters <chris@cwinters.com>