ePages 6.17.43 - DE_EPAGES/Core/API/Error.pm

Package DE_EPAGES::Core::API::Error

This module provides exception-like error handling. Error messages are formatted using a template which is defined by the ErrorDefinition function in the module that threw an error. The template may contain placeholders for additional information, such as file name, SQL statement or other information that may be useful for tracking an error. These parameters are passed to the Error function.

Example
use DE_EPAGES::Core::API::Error qw( Error ExistsError GetError );

# How to define error codes and message templates

sub ErrorDefinition { return {
    MissingParameter => 'Missing parameter #Parameter',
    ValueTooLong     => 'Value length #Length is larger than #MaxLength'
}}

# How to throw errors

sub MyFunction {
    my ( $Name, $Value ) = @_;
    Error('MissingParameter', { Parameter => 'Name' } ) unless defined $Name;
    Error('ValueTooLong', {
        Length    => length $Value,
        MaxLength => 25
    } ) if length $Value > 25;
    ...
}

# How to handle errors

$SIG{__DIE__} = \&DE_EPAGES::Core::API::Error::DieHandler;

eval {
   MyFunction();
};
HandleError(
    OnError => sub {
        my ($Error) = @_;
        print $Error->message;
    }
);
@EXPORT_OK
Error
CallerError
ExistsError
GetError
ResetError
VarsOnError
CleanupOnError
RunScript
HandleError
QuoteStringForError

Functions

CallerError
CleanupOnError
DieHandler
Error
ExistsError
GetError
HandleError
QuoteStringForError
ResetError
RunScript
VarsOnError
addReEntry
addVars
callers
code
file
guid
hash
innerLongMessage
line
longMessage
message
new
package
reEntries
shortMessage
subname
vars

CallerError

Reports an error that was caused by the caller.

Syntax
CallerError( $Code, $hVars );
CallerError( $Code, $hVars, $hOptions );
Example
CallerError( 'MissingParameter', { Param => 'CatalogID' } ) unless $CatalogID;
CallerError( 'MissingParameter', { Param => 'CatalogID' }, { SkipCallers => 1 );
Input
$Code (string)
The $Code parameter can hold an arbitrary string as short code for
the error. This code must be defined inside an "ErrorDefinition"
function inside the module that calls this function.
$hVars (string)
An optional hash reference that holds any additional parameters.
These values are used to replace parameters in the error message
template.
$hOptions (ref.hash)
(optional)
  • SkipCallers - (default=0) number of call levels to skip

CleanupOnError

Executes the function $Sub if an error occured in the previous 'eval' block. Afterwards re-throws the original error. Creates a warning if $Sub throws an error. See also HandleError.

Syntax
CleanupOnError( $Sub );
Example
eval {
    ...
};
CleanupOnError( sub {
    my ($Error) = @_;
    ...
});
Input
$Sub (ref.code)
cleanup function, the first parameter is the error object

DieHandler

Set this function as handler for the __DIE__ signal. It converts a native "die" into an error object.

Syntax
DieHandler( $Message )
Example
$SIG{__DIE__} = \&DE_EPAGES::Core::API::Error::DieHandler;
Input
$Message (string)
the error message that was passed to the "die" function.

Error

Call this function to raise an error. In case of a 'die' error, the function DieHandler will generate the error object automatically. The Error function may also be called to escalate an error, in this case the function gets the error object as its only parameter.

Syntax
Error( $Code, $hVars );  # report a new error
Error( $Code, $hVars, $InnerError );  # report a new error and encapsulate a previous error
Error( $Error );         # escalating an unhandled error
Example
Error( 'MissingParameter', { Param => 'CatalogID' } ) unless $CatalogID;
Error( 'Timeout' );
Error( $Error ) unless $Error->code eq 'Timeout';
Input
$Code (string)
The $Code parameter can hold an arbitrary string as short code for
the error. This code must be defined inside an "ErrorDefinition"
function inside the module that calls this function.
$Code can be an Error object. In this case the error will be
escalated to the next level of eval.
$hVars (string)
An optional hash reference that holds any additional parameters.
These values are used to replace parameters in the error message
template.
$InnerError (string or Error object)
(optional) Inner error object or long message

ExistsError

Returns true if an error occured inside an 'eval' block. Uses $@ to check for an existing error.

Syntax
$ExistsError = ExistsError()
Example
eval { ... }; if( ExistsError ) { ... }
Return
$ExistsError (boolean)
true if an error occured

GetError

Returns the Error object if an error occured in the previous 'eval' block. Returns 'undef' if no error occured.

Syntax
$Error = GetError()
Example
print GetError->message if ExistsError;
Return
$Error (object)
the global error object

HandleError

Executes callback functions, then escalates the original error. Any errors that occured during error handling are converted to warnings.

Syntax
HandleError( %Options );
Example
eval {
    CreateTempFile();
    WriteFile('file1');
    WriteFile('file2');
};
HandleError(
    OnError => sub {
        return 'FIXED' if ExistsFile('file2');
        DeleteFile('file1');
    },
    Finally => sub {
        DeleteTempFile();
    }
);
Input
%Options (hash)
  • OnError - (optional) function that is executed only if there was
    an error in the eval{} block.
    Receives the error object as first parameter.
    If the function returns the string 'FIXED', then the original
    error is not escalated.
  • Finally - (optional) function that is always executed, if there
    was an error or not.
    This function is executed after the OnError function.
    Receives the error object as first parameter.

QuoteStringForError

Checks if the given string contains non-printable chars like NUL, BEL, ... Escapes all found chars in the input string and returns an array with all found chars, too.

Syntax
my ($CleanString, $aFoundChars) = QuoteStringForError($String);
Input
$String (string)
input string
Return
@Result (array)
cleaned string, found chars as ref.array

ResetError

Resets the global error state. When this function was called, then GetError will return 'undef'. Note that it is normally not necessary to use this function because $@ is automatically reset by the 'eval' function.

Syntax
ResetError()

RunScript

Runs the main function in the context of the Error module and enables detailed error information. See also DE_EPAGES::Core::API::Script::RunScript.

Syntax
RunScript( %Options );
Example
RunScript( Sub => \&Main )
RunScript( Debug => 1, Sub => \&Main )
Input
%Options (hash)
  • Sub - a code reference of the main function - code ref
  • Debug - (optional) enables extended error information with stack trace
    using longMessage - boolean

VarsOnError

If an error occured in the previous 'eval' block, the variables of the parameter will be added to the error variables. The error will be raised again.

Syntax
VarsOnError($hVars)
Example
eval { doanything($file) }; VarsOnError({'file'=>$file});
Input
$hVars (ref.hash)
vars

addReEntry

Adds a stack to error re-entries. Rememebers the point which calls Error(GetError()).

Syntax
$Error->addReEntry($Stack);
Example
$Error->addReEntry(GetCallerStack());
Input
$Stack (ref.array.hash)
caller stack

addVars

Copies all keys and values from the $hVars hash to the parameter hash. Overrides any existing parameter values.

Syntax
$Error->addVars( $hVars );
Example
$Error->addVars( { 'FileName' => $FileName } );
Input
$hVars (hash ref)
error parameters

callers

Returns the stack trace as an array ref of caller array references. The caller index 1 contains the file/line where the error was actually raised. See DE_EPAGES::Core::API::PerlTools::GetCallerStack for the meaning of the caller stack entries.

Syntax
$aaCallers = $Error->callers;
Example
print "Error in file: " . GetError->callers->[1][CALLER_FILENAME];
print GetCallerString(GetError->callers, 1);
Return
$aaCallers (ref.array.array)
caller stack

code

Returns the error code that was passed to Error or new.

Syntax
$Code = $Error->code;
Input
$Code (string)
error code

file

Returns the file name of error.

Syntax
$filename = $Error->file
Return
$filename (string)
file name

guid

Returns the unique error id.

Syntax
$Code = $Error->guid;
Input
$Code (string)
error code

hash

Returns a hash string of the call stack.

Syntax
$Hash = $Error->hash;
Input
$Hash (string)
hash

innerLongMessage

Returns the full message of the inner error including stack trace.

Syntax
$LongMessage = $Error->innerLongMessage;
Return
$LongMessage (string)
detailed error message including stack trace
(undef if no inner error exists)

line

Returns the line number of error.

Syntax
$lineno = $Error->line
Return
$lineno (integer)
line number

longMessage

Returns the message including file name, line number, stack trace and all parameter values.

Syntax
$Message = $Error->longMessage
Input
%Options (hash)
toggles option 'SkipStackTrace'
Return
$Message (string)
long error message

message

Returns the message including file name and line number in the same format as Perl would print a "die" error. The message will include the file name and line number that raised the error.

Syntax
$Message = $Error->message
Example
print GetError->message if ExistsError;
Return
$Message (string)
error message

new

Creates a new error object. Normally you don't use this constructor directly. Rather you will use Error and GetError.

Syntax
$Error = DE_EPAGES::Core::API::Error->new(
    Code => $Code,
    Vars => $hVars,
    Message => $Message,
    InnerLongMessage => $InnerLongMessage,
    SkipCallers => $SkipCallers,
    ErrorDefinitionPackage => $ErrorDefinitionPackage,
);
Example
$Error = DE_EPAGES::Core::API::Error->new( Code => 'DiskFull' );
Input
$Code (string)
an error code
$hVars (hash ref)
optional hash reference with additional parameters
$Message (string)
optional message text
$InnerLongMessage (string)
(optional) full error message of the inner error
$SkipCallers (int)
(optional, default: 0) number of call levels to skip
$ErrorDefinitionPackage (string)
(optional, default: caller(1)) package name
that contains a message template for the error code
Return
$Error (object)
an error object

package

Returns the package name of error.

Syntax
$packagename = $Error->package
Return
$packagename (string)
package name

reEntries

Returns the stack traces of error re-entries. That means the points which can't handle the error an set it again with Error(GetError()). Each caller entry has the format of:

{
FileName => $FileName,
Line     => $LineNo,
SubName  => $SubName,
Package  => $PackageName
}
The caller index 1 contains the file/line where the error was actually raised.

Syntax
$aCallers = $Error->reEntries;
Return
$aCallers (ref.array.array.hash)
caller stacks

shortMessage

Returns the message without file name and line number. If the error was thrown by the Error function, the message is retrieved from the "ErrorDefinition" function in the module that threw the error. Any placeholders are replaced by variables in the parameter $hVars that were passed to Error.

Syntax
$Message = $Error->shortMessage
Return
$Message (string)
short error message

subname

Returns the function name of error (ignores eval calls in stack).

Syntax
$subname = $Error->subname
Return
$subname (string)
function name

vars

Returns the parameter hash that was passed to Error or new.

Syntax
$hVars = $Error->vars;
Return
$hVars (hash ref)
error parameters