package RG::Exception;
##############################################################################
#
# Copyright: 2008 László Kaján
#
# License: This program is free software; you can redistribute it and/or
# modify it under the same terms as Perl itself, either Perl version 5.8.8 or,
# at your option, any later version of Perl 5 you may have available.
#
##############################################################################
# RG exception base class
# Typical use:
#   die RG::Exception->new( { msg => 'error message' } );
##############################################################################
use strict;
use Carp;
$Carp::CarpInternal{ 'RG::Exception' }++;

sub               new
{
  my $this = shift;
  my $class = ref($this) || $this;
  my $self = {};
  bless $self, $class;
  $self->_initialize( @_ );
  return $self;
}


sub               _initialize   # protected method
{
  my( $self, %__p ) = @_;
  # { msg => str }

  if( !$__p{msg} ) { $__p{msg} = ''; }

  # set properties
  while( my( $key, $val ) = each( %__p ) ) { $self->$key( $val ); }
}


# Overloaded string conversion operator. Returns "Uncaught exception 'REFERENCE':".msg(). Normally you would catch the exception and emit the message msg() of it.
use overload '""' => sub{ return 'Uncaught exception \''.ref($_[0])."\':\n".$_[0]->msg_stack_backtrace(); };


sub               msg             # error message
{
  if( @_ > 1 )
  {
    $_[0]->msg_stack_backtrace( Carp::longmess( $_[1] ) );
    return $_[0]->{_msg} = Carp::shortmess( $_[1] );
  }
  else
  {
    return $_[0]->{_msg};
  }
}


# Error message appended with the output of Carp::longmess(), a stack backtrace. See: L<Carp>.
sub               msg_stack_backtrace             # error message
{ return ( @_ > 1 ? $_[0]->{_msg_stack_backtrace} = $_[1] : $_[0]->{_msg_stack_backtrace} ); }


package RG::Exception::NotImplemented;
use strict;
use Carp;
$Carp::CarpInternal{ 'RG::Exception::NotImplemented' }++;
use base qw( RG::Exception ); # inheritance
##############################################################################
# Typical use:
#   die RG::Exception::NotImplemented->new();
##############################################################################
sub               _initialize   # protected method
{
  my( $self ) = @_;

  $self->SUPER::_initialize( msg => 'not implemented' );
}


package RG::Exception::SyntaxError;
use strict;
use Carp;
$Carp::CarpInternal{ 'RG::Exception::SyntaxError' }++;
use base qw( RG::Exception ); # inheritance
##############################################################################
# Typical use:
#   die RG::Exception::Parser::SyntaxError->new( { msg => 'syntax error on line $lineno' } );
##############################################################################

1;

# vim:et:ts=2:ai:
