Exceptions

When an error occurs, the IMu Perl API throws an exception (die in Perl terminology). The exception is an IMu::Exception object.

For simple error handling all that is usually required is to catch the exception and report the exception as a string:

eval
{
    # ⋯
};if ($@)
{
    die("Error: $@");
}

The IMu::Exception class overrides the Perl "" (stringify) operator (which is called "magically" when the exception object is used as a string) and returns an error message.

To handle specific IMu errors it is necessary to check the exception is an IMu::Exception object before using it. The IMu::Exception class includes a property called id. This is a string and contains the internal IMu error code for the exception. For example, you may want to catch the exception raised when an IMu::Session object's connect method fails and try to connect to an alternative server:

my $mainServer = 'server1.com';
my $alternativeServer = 'server2.com';
my $session = IMu::Session->new();
$session->{'host'} = $mainServer;
eval
{
    $session->connect();
};
if ($@)
{
    if (ref($@) && $@->isa('IMu::Exception'))
    {
        # Check for specific SessionConnect error
        if ($@->getID() eq 'SessionConnect')
        {
            $session->{'host'} = $alternativeServer;
            eval
            {
                $session->connect();
            };
        }
    }
    # Check for exception again. If we successfully connected
    # to $alternativeServer then $@ will be cleared.
    if ($@)
    {
        die("Error: $@\n");
    }
}
# By the time we get to here the session is connected to either
# the main server or the alternative.