PageRenderTime 57ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/third-party/Error.pm

http://yasco.googlecode.com/
Perl | 1012 lines | 753 code | 199 blank | 60 comment | 67 complexity | 057ff29dcd26de49eb2015b94608f94e MD5 | raw file
  1. # Error.pm
  2. #
  3. # Copyright (c) 1997-8 Graham Barr <gbarr@ti.com>. All rights reserved.
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the same terms as Perl itself.
  6. #
  7. # Based on my original Error.pm, and Exceptions.pm by Peter Seibel
  8. # <peter@weblogic.com> and adapted by Jesse Glick <jglick@sig.bsh.com>.
  9. #
  10. # but modified ***significantly***
  11. package Error;
  12. use strict;
  13. use vars qw($VERSION);
  14. use 5.004;
  15. $VERSION = "0.17015";
  16. use overload (
  17. '""' => 'stringify',
  18. '0+' => 'value',
  19. 'bool' => sub { return 1; },
  20. 'fallback' => 1
  21. );
  22. $Error::Depth = 0; # Depth to pass to caller()
  23. $Error::Debug = 0; # Generate verbose stack traces
  24. @Error::STACK = (); # Clause stack for try
  25. $Error::THROWN = undef; # last error thrown, a workaround until die $ref works
  26. my $LAST; # Last error created
  27. my %ERROR; # Last error associated with package
  28. sub _throw_Error_Simple
  29. {
  30. my $args = shift;
  31. return Error::Simple->new($args->{'text'});
  32. }
  33. $Error::ObjectifyCallback = \&_throw_Error_Simple;
  34. # Exported subs are defined in Error::subs
  35. use Scalar::Util ();
  36. sub import {
  37. shift;
  38. my @tags = @_;
  39. local $Exporter::ExportLevel = $Exporter::ExportLevel + 1;
  40. @tags = grep {
  41. if( $_ eq ':warndie' ) {
  42. Error::WarnDie->import();
  43. 0;
  44. }
  45. else {
  46. 1;
  47. }
  48. } @tags;
  49. Error::subs->import(@tags);
  50. }
  51. # I really want to use last for the name of this method, but it is a keyword
  52. # which prevent the syntax last Error
  53. sub prior {
  54. shift; # ignore
  55. return $LAST unless @_;
  56. my $pkg = shift;
  57. return exists $ERROR{$pkg} ? $ERROR{$pkg} : undef
  58. unless ref($pkg);
  59. my $obj = $pkg;
  60. my $err = undef;
  61. if($obj->isa('HASH')) {
  62. $err = $obj->{'__Error__'}
  63. if exists $obj->{'__Error__'};
  64. }
  65. elsif($obj->isa('GLOB')) {
  66. $err = ${*$obj}{'__Error__'}
  67. if exists ${*$obj}{'__Error__'};
  68. }
  69. $err;
  70. }
  71. sub flush {
  72. shift; #ignore
  73. unless (@_) {
  74. $LAST = undef;
  75. return;
  76. }
  77. my $pkg = shift;
  78. return unless ref($pkg);
  79. undef $ERROR{$pkg} if defined $ERROR{$pkg};
  80. }
  81. # Return as much information as possible about where the error
  82. # happened. The -stacktrace element only exists if $Error::DEBUG
  83. # was set when the error was created
  84. sub stacktrace {
  85. my $self = shift;
  86. return $self->{'-stacktrace'}
  87. if exists $self->{'-stacktrace'};
  88. my $text = exists $self->{'-text'} ? $self->{'-text'} : "Died";
  89. $text .= sprintf(" at %s line %d.\n", $self->file, $self->line)
  90. unless($text =~ /\n$/s);
  91. $text;
  92. }
  93. sub associate {
  94. my $err = shift;
  95. my $obj = shift;
  96. return unless ref($obj);
  97. if($obj->isa('HASH')) {
  98. $obj->{'__Error__'} = $err;
  99. }
  100. elsif($obj->isa('GLOB')) {
  101. ${*$obj}{'__Error__'} = $err;
  102. }
  103. $obj = ref($obj);
  104. $ERROR{ ref($obj) } = $err;
  105. return;
  106. }
  107. sub new {
  108. my $self = shift;
  109. my($pkg,$file,$line) = caller($Error::Depth);
  110. my $err = bless {
  111. '-package' => $pkg,
  112. '-file' => $file,
  113. '-line' => $line,
  114. @_
  115. }, $self;
  116. $err->associate($err->{'-object'})
  117. if(exists $err->{'-object'});
  118. # To always create a stacktrace would be very inefficient, so
  119. # we only do it if $Error::Debug is set
  120. if($Error::Debug) {
  121. require Carp;
  122. local $Carp::CarpLevel = $Error::Depth;
  123. my $text = defined($err->{'-text'}) ? $err->{'-text'} : "Error";
  124. my $trace = Carp::longmess($text);
  125. # Remove try calls from the trace
  126. $trace =~ s/(\n\s+\S+__ANON__[^\n]+)?\n\s+eval[^\n]+\n\s+Error::subs::try[^\n]+(?=\n)//sog;
  127. $trace =~ s/(\n\s+\S+__ANON__[^\n]+)?\n\s+eval[^\n]+\n\s+Error::subs::run_clauses[^\n]+\n\s+Error::subs::try[^\n]+(?=\n)//sog;
  128. $err->{'-stacktrace'} = $trace
  129. }
  130. $@ = $LAST = $ERROR{$pkg} = $err;
  131. }
  132. # Throw an error. this contains some very gory code.
  133. sub throw {
  134. my $self = shift;
  135. local $Error::Depth = $Error::Depth + 1;
  136. # if we are not rethrow-ing then create the object to throw
  137. $self = $self->new(@_) unless ref($self);
  138. die $Error::THROWN = $self;
  139. }
  140. # syntactic sugar for
  141. #
  142. # die with Error( ... );
  143. sub with {
  144. my $self = shift;
  145. local $Error::Depth = $Error::Depth + 1;
  146. $self->new(@_);
  147. }
  148. # syntactic sugar for
  149. #
  150. # record Error( ... ) and return;
  151. sub record {
  152. my $self = shift;
  153. local $Error::Depth = $Error::Depth + 1;
  154. $self->new(@_);
  155. }
  156. # catch clause for
  157. #
  158. # try { ... } catch CLASS with { ... }
  159. sub catch {
  160. my $pkg = shift;
  161. my $code = shift;
  162. my $clauses = shift || {};
  163. my $catch = $clauses->{'catch'} ||= [];
  164. unshift @$catch, $pkg, $code;
  165. $clauses;
  166. }
  167. # Object query methods
  168. sub object {
  169. my $self = shift;
  170. exists $self->{'-object'} ? $self->{'-object'} : undef;
  171. }
  172. sub file {
  173. my $self = shift;
  174. exists $self->{'-file'} ? $self->{'-file'} : undef;
  175. }
  176. sub line {
  177. my $self = shift;
  178. exists $self->{'-line'} ? $self->{'-line'} : undef;
  179. }
  180. sub text {
  181. my $self = shift;
  182. exists $self->{'-text'} ? $self->{'-text'} : undef;
  183. }
  184. # overload methods
  185. sub stringify {
  186. my $self = shift;
  187. defined $self->{'-text'} ? $self->{'-text'} : "Died";
  188. }
  189. sub value {
  190. my $self = shift;
  191. exists $self->{'-value'} ? $self->{'-value'} : undef;
  192. }
  193. package Error::Simple;
  194. @Error::Simple::ISA = qw(Error);
  195. sub new {
  196. my $self = shift;
  197. my $text = "" . shift;
  198. my $value = shift;
  199. my(@args) = ();
  200. local $Error::Depth = $Error::Depth + 1;
  201. @args = ( -file => $1, -line => $2)
  202. if($text =~ s/\s+at\s+(\S+)\s+line\s+(\d+)(?:,\s*<[^>]*>\s+line\s+\d+)?\.?\n?$//s);
  203. push(@args, '-value', 0 + $value)
  204. if defined($value);
  205. $self->SUPER::new(-text => $text, @args);
  206. }
  207. sub stringify {
  208. my $self = shift;
  209. my $text = $self->SUPER::stringify;
  210. $text .= sprintf(" at %s line %d.\n", $self->file, $self->line)
  211. unless($text =~ /\n$/s);
  212. $text;
  213. }
  214. ##########################################################################
  215. ##########################################################################
  216. # Inspired by code from Jesse Glick <jglick@sig.bsh.com> and
  217. # Peter Seibel <peter@weblogic.com>
  218. package Error::subs;
  219. use Exporter ();
  220. use vars qw(@EXPORT_OK @ISA %EXPORT_TAGS);
  221. @EXPORT_OK = qw(try with finally except otherwise);
  222. %EXPORT_TAGS = (try => \@EXPORT_OK);
  223. @ISA = qw(Exporter);
  224. sub run_clauses ($$$\@) {
  225. my($clauses,$err,$wantarray,$result) = @_;
  226. my $code = undef;
  227. $err = $Error::ObjectifyCallback->({'text' =>$err}) unless ref($err);
  228. CATCH: {
  229. # catch
  230. my $catch;
  231. if(defined($catch = $clauses->{'catch'})) {
  232. my $i = 0;
  233. CATCHLOOP:
  234. for( ; $i < @$catch ; $i += 2) {
  235. my $pkg = $catch->[$i];
  236. unless(defined $pkg) {
  237. #except
  238. splice(@$catch,$i,2,$catch->[$i+1]->($err));
  239. $i -= 2;
  240. next CATCHLOOP;
  241. }
  242. elsif(Scalar::Util::blessed($err) && $err->isa($pkg)) {
  243. $code = $catch->[$i+1];
  244. while(1) {
  245. my $more = 0;
  246. local($Error::THROWN, $@);
  247. my $ok = eval {
  248. $@ = $err;
  249. if($wantarray) {
  250. @{$result} = $code->($err,\$more);
  251. }
  252. elsif(defined($wantarray)) {
  253. @{$result} = ();
  254. $result->[0] = $code->($err,\$more);
  255. }
  256. else {
  257. $code->($err,\$more);
  258. }
  259. 1;
  260. };
  261. if( $ok ) {
  262. next CATCHLOOP if $more;
  263. undef $err;
  264. }
  265. else {
  266. $err = $@ || $Error::THROWN;
  267. $err = $Error::ObjectifyCallback->({'text' =>$err})
  268. unless ref($err);
  269. }
  270. last CATCH;
  271. };
  272. }
  273. }
  274. }
  275. # otherwise
  276. my $owise;
  277. if(defined($owise = $clauses->{'otherwise'})) {
  278. my $code = $clauses->{'otherwise'};
  279. my $more = 0;
  280. local($Error::THROWN, $@);
  281. my $ok = eval {
  282. $@ = $err;
  283. if($wantarray) {
  284. @{$result} = $code->($err,\$more);
  285. }
  286. elsif(defined($wantarray)) {
  287. @{$result} = ();
  288. $result->[0] = $code->($err,\$more);
  289. }
  290. else {
  291. $code->($err,\$more);
  292. }
  293. 1;
  294. };
  295. if( $ok ) {
  296. undef $err;
  297. }
  298. else {
  299. $err = $@ || $Error::THROWN;
  300. $err = $Error::ObjectifyCallback->({'text' =>$err})
  301. unless ref($err);
  302. }
  303. }
  304. }
  305. $err;
  306. }
  307. sub try (&;$) {
  308. my $try = shift;
  309. my $clauses = @_ ? shift : {};
  310. my $ok = 0;
  311. my $err = undef;
  312. my @result = ();
  313. unshift @Error::STACK, $clauses;
  314. my $wantarray = wantarray();
  315. do {
  316. local $Error::THROWN = undef;
  317. local $@ = undef;
  318. $ok = eval {
  319. if($wantarray) {
  320. @result = $try->();
  321. }
  322. elsif(defined $wantarray) {
  323. $result[0] = $try->();
  324. }
  325. else {
  326. $try->();
  327. }
  328. 1;
  329. };
  330. $err = $@ || $Error::THROWN
  331. unless $ok;
  332. };
  333. shift @Error::STACK;
  334. $err = run_clauses($clauses,$err,wantarray,@result)
  335. unless($ok);
  336. $clauses->{'finally'}->()
  337. if(defined($clauses->{'finally'}));
  338. if (defined($err))
  339. {
  340. if (Scalar::Util::blessed($err) && $err->can('throw'))
  341. {
  342. throw $err;
  343. }
  344. else
  345. {
  346. die $err;
  347. }
  348. }
  349. wantarray ? @result : $result[0];
  350. }
  351. # Each clause adds a sub to the list of clauses. The finally clause is
  352. # always the last, and the otherwise clause is always added just before
  353. # the finally clause.
  354. #
  355. # All clauses, except the finally clause, add a sub which takes one argument
  356. # this argument will be the error being thrown. The sub will return a code ref
  357. # if that clause can handle that error, otherwise undef is returned.
  358. #
  359. # The otherwise clause adds a sub which unconditionally returns the users
  360. # code reference, this is why it is forced to be last.
  361. #
  362. # The catch clause is defined in Error.pm, as the syntax causes it to
  363. # be called as a method
  364. sub with (&;$) {
  365. @_
  366. }
  367. sub finally (&) {
  368. my $code = shift;
  369. my $clauses = { 'finally' => $code };
  370. $clauses;
  371. }
  372. # The except clause is a block which returns a hashref or a list of
  373. # key-value pairs, where the keys are the classes and the values are subs.
  374. sub except (&;$) {
  375. my $code = shift;
  376. my $clauses = shift || {};
  377. my $catch = $clauses->{'catch'} ||= [];
  378. my $sub = sub {
  379. my $ref;
  380. my(@array) = $code->($_[0]);
  381. if(@array == 1 && ref($array[0])) {
  382. $ref = $array[0];
  383. $ref = [ %$ref ]
  384. if(UNIVERSAL::isa($ref,'HASH'));
  385. }
  386. else {
  387. $ref = \@array;
  388. }
  389. @$ref
  390. };
  391. unshift @{$catch}, undef, $sub;
  392. $clauses;
  393. }
  394. sub otherwise (&;$) {
  395. my $code = shift;
  396. my $clauses = shift || {};
  397. if(exists $clauses->{'otherwise'}) {
  398. require Carp;
  399. Carp::croak("Multiple otherwise clauses");
  400. }
  401. $clauses->{'otherwise'} = $code;
  402. $clauses;
  403. }
  404. 1;
  405. package Error::WarnDie;
  406. sub gen_callstack($)
  407. {
  408. my ( $start ) = @_;
  409. require Carp;
  410. local $Carp::CarpLevel = $start;
  411. my $trace = Carp::longmess("");
  412. # Remove try calls from the trace
  413. $trace =~ s/(\n\s+\S+__ANON__[^\n]+)?\n\s+eval[^\n]+\n\s+Error::subs::try[^\n]+(?=\n)//sog;
  414. $trace =~ s/(\n\s+\S+__ANON__[^\n]+)?\n\s+eval[^\n]+\n\s+Error::subs::run_clauses[^\n]+\n\s+Error::subs::try[^\n]+(?=\n)//sog;
  415. my @callstack = split( m/\n/, $trace );
  416. return @callstack;
  417. }
  418. my $old_DIE;
  419. my $old_WARN;
  420. sub DEATH
  421. {
  422. my ( $e ) = @_;
  423. local $SIG{__DIE__} = $old_DIE if( defined $old_DIE );
  424. die @_ if $^S;
  425. my ( $etype, $message, $location, @callstack );
  426. if ( ref($e) && $e->isa( "Error" ) ) {
  427. $etype = "exception of type " . ref( $e );
  428. $message = $e->text;
  429. $location = $e->file . ":" . $e->line;
  430. @callstack = split( m/\n/, $e->stacktrace );
  431. }
  432. else {
  433. # Don't apply subsequent layer of message formatting
  434. die $e if( $e =~ m/^\nUnhandled perl error caught at toplevel:\n\n/ );
  435. $etype = "perl error";
  436. my $stackdepth = 0;
  437. while( caller( $stackdepth ) =~ m/^Error(?:$|::)/ ) {
  438. $stackdepth++
  439. }
  440. @callstack = gen_callstack( $stackdepth + 1 );
  441. $message = "$e";
  442. chomp $message;
  443. if ( $message =~ s/ at (.*?) line (\d+)\.$// ) {
  444. $location = $1 . ":" . $2;
  445. }
  446. else {
  447. my @caller = caller( $stackdepth );
  448. $location = $caller[1] . ":" . $caller[2];
  449. }
  450. }
  451. shift @callstack;
  452. # Do it this way in case there are no elements; we don't print a spurious \n
  453. my $callstack = join( "", map { "$_\n"} @callstack );
  454. die "\nUnhandled $etype caught at toplevel:\n\n $message\n\nThrown from: $location\n\nFull stack trace:\n\n$callstack\n";
  455. }
  456. sub TAXES
  457. {
  458. my ( $message ) = @_;
  459. local $SIG{__WARN__} = $old_WARN if( defined $old_WARN );
  460. $message =~ s/ at .*? line \d+\.$//;
  461. chomp $message;
  462. my @callstack = gen_callstack( 1 );
  463. my $location = shift @callstack;
  464. # $location already starts in a leading space
  465. $message .= $location;
  466. # Do it this way in case there are no elements; we don't print a spurious \n
  467. my $callstack = join( "", map { "$_\n"} @callstack );
  468. warn "$message:\n$callstack";
  469. }
  470. sub import
  471. {
  472. $old_DIE = $SIG{__DIE__};
  473. $old_WARN = $SIG{__WARN__};
  474. $SIG{__DIE__} = \&DEATH;
  475. $SIG{__WARN__} = \&TAXES;
  476. }
  477. 1;
  478. __END__
  479. =head1 NAME
  480. Error - Error/exception handling in an OO-ish way
  481. =head1 SYNOPSIS
  482. use Error qw(:try);
  483. throw Error::Simple( "A simple error");
  484. sub xyz {
  485. ...
  486. record Error::Simple("A simple error")
  487. and return;
  488. }
  489. unlink($file) or throw Error::Simple("$file: $!",$!);
  490. try {
  491. do_some_stuff();
  492. die "error!" if $condition;
  493. throw Error::Simple "Oops!" if $other_condition;
  494. }
  495. catch Error::IO with {
  496. my $E = shift;
  497. print STDERR "File ", $E->{'-file'}, " had a problem\n";
  498. }
  499. except {
  500. my $E = shift;
  501. my $general_handler=sub {send_message $E->{-description}};
  502. return {
  503. UserException1 => $general_handler,
  504. UserException2 => $general_handler
  505. };
  506. }
  507. otherwise {
  508. print STDERR "Well I don't know what to say\n";
  509. }
  510. finally {
  511. close_the_garage_door_already(); # Should be reliable
  512. }; # Don't forget the trailing ; or you might be surprised
  513. =head1 DESCRIPTION
  514. The C<Error> package provides two interfaces. Firstly C<Error> provides
  515. a procedural interface to exception handling. Secondly C<Error> is a
  516. base class for errors/exceptions that can either be thrown, for
  517. subsequent catch, or can simply be recorded.
  518. Errors in the class C<Error> should not be thrown directly, but the
  519. user should throw errors from a sub-class of C<Error>.
  520. =head1 PROCEDURAL INTERFACE
  521. C<Error> exports subroutines to perform exception handling. These will
  522. be exported if the C<:try> tag is used in the C<use> line.
  523. =over 4
  524. =item try BLOCK CLAUSES
  525. C<try> is the main subroutine called by the user. All other subroutines
  526. exported are clauses to the try subroutine.
  527. The BLOCK will be evaluated and, if no error is throw, try will return
  528. the result of the block.
  529. C<CLAUSES> are the subroutines below, which describe what to do in the
  530. event of an error being thrown within BLOCK.
  531. =item catch CLASS with BLOCK
  532. This clauses will cause all errors that satisfy C<$err-E<gt>isa(CLASS)>
  533. to be caught and handled by evaluating C<BLOCK>.
  534. C<BLOCK> will be passed two arguments. The first will be the error
  535. being thrown. The second is a reference to a scalar variable. If this
  536. variable is set by the catch block then, on return from the catch
  537. block, try will continue processing as if the catch block was never
  538. found. The error will also be available in C<$@>.
  539. To propagate the error the catch block may call C<$err-E<gt>throw>
  540. If the scalar reference by the second argument is not set, and the
  541. error is not thrown. Then the current try block will return with the
  542. result from the catch block.
  543. =item except BLOCK
  544. When C<try> is looking for a handler, if an except clause is found
  545. C<BLOCK> is evaluated. The return value from this block should be a
  546. HASHREF or a list of key-value pairs, where the keys are class names
  547. and the values are CODE references for the handler of errors of that
  548. type.
  549. =item otherwise BLOCK
  550. Catch any error by executing the code in C<BLOCK>
  551. When evaluated C<BLOCK> will be passed one argument, which will be the
  552. error being processed. The error will also be available in C<$@>.
  553. Only one otherwise block may be specified per try block
  554. =item finally BLOCK
  555. Execute the code in C<BLOCK> either after the code in the try block has
  556. successfully completed, or if the try block throws an error then
  557. C<BLOCK> will be executed after the handler has completed.
  558. If the handler throws an error then the error will be caught, the
  559. finally block will be executed and the error will be re-thrown.
  560. Only one finally block may be specified per try block
  561. =back
  562. =head1 CLASS INTERFACE
  563. =head2 CONSTRUCTORS
  564. The C<Error> object is implemented as a HASH. This HASH is initialized
  565. with the arguments that are passed to it's constructor. The elements
  566. that are used by, or are retrievable by the C<Error> class are listed
  567. below, other classes may add to these.
  568. -file
  569. -line
  570. -text
  571. -value
  572. -object
  573. If C<-file> or C<-line> are not specified in the constructor arguments
  574. then these will be initialized with the file name and line number where
  575. the constructor was called from.
  576. If the error is associated with an object then the object should be
  577. passed as the C<-object> argument. This will allow the C<Error> package
  578. to associate the error with the object.
  579. The C<Error> package remembers the last error created, and also the
  580. last error associated with a package. This could either be the last
  581. error created by a sub in that package, or the last error which passed
  582. an object blessed into that package as the C<-object> argument.
  583. =over 4
  584. =item Error->new()
  585. See the Error::Simple documentation.
  586. =item throw ( [ ARGS ] )
  587. Create a new C<Error> object and throw an error, which will be caught
  588. by a surrounding C<try> block, if there is one. Otherwise it will cause
  589. the program to exit.
  590. C<throw> may also be called on an existing error to re-throw it.
  591. =item with ( [ ARGS ] )
  592. Create a new C<Error> object and returns it. This is defined for
  593. syntactic sugar, eg
  594. die with Some::Error ( ... );
  595. =item record ( [ ARGS ] )
  596. Create a new C<Error> object and returns it. This is defined for
  597. syntactic sugar, eg
  598. record Some::Error ( ... )
  599. and return;
  600. =back
  601. =head2 STATIC METHODS
  602. =over 4
  603. =item prior ( [ PACKAGE ] )
  604. Return the last error created, or the last error associated with
  605. C<PACKAGE>
  606. =item flush ( [ PACKAGE ] )
  607. Flush the last error created, or the last error associated with
  608. C<PACKAGE>.It is necessary to clear the error stack before exiting the
  609. package or uncaught errors generated using C<record> will be reported.
  610. $Error->flush;
  611. =cut
  612. =back
  613. =head2 OBJECT METHODS
  614. =over 4
  615. =item stacktrace
  616. If the variable C<$Error::Debug> was non-zero when the error was
  617. created, then C<stacktrace> returns a string created by calling
  618. C<Carp::longmess>. If the variable was zero the C<stacktrace> returns
  619. the text of the error appended with the filename and line number of
  620. where the error was created, providing the text does not end with a
  621. newline.
  622. =item object
  623. The object this error was associated with
  624. =item file
  625. The file where the constructor of this error was called from
  626. =item line
  627. The line where the constructor of this error was called from
  628. =item text
  629. The text of the error
  630. =item $err->associate($obj)
  631. Associates an error with an object to allow error propagation. I.e:
  632. $ber->encode(...) or
  633. return Error->prior($ber)->associate($ldap);
  634. =back
  635. =head2 OVERLOAD METHODS
  636. =over 4
  637. =item stringify
  638. A method that converts the object into a string. This method may simply
  639. return the same as the C<text> method, or it may append more
  640. information. For example the file name and line number.
  641. By default this method returns the C<-text> argument that was passed to
  642. the constructor, or the string C<"Died"> if none was given.
  643. =item value
  644. A method that will return a value that can be associated with the
  645. error. For example if an error was created due to the failure of a
  646. system call, then this may return the numeric value of C<$!> at the
  647. time.
  648. By default this method returns the C<-value> argument that was passed
  649. to the constructor.
  650. =back
  651. =head1 PRE-DEFINED ERROR CLASSES
  652. =head2 Error::Simple
  653. This class can be used to hold simple error strings and values. It's
  654. constructor takes two arguments. The first is a text value, the second
  655. is a numeric value. These values are what will be returned by the
  656. overload methods.
  657. If the text value ends with C<at file line 1> as $@ strings do, then
  658. this infomation will be used to set the C<-file> and C<-line> arguments
  659. of the error object.
  660. This class is used internally if an eval'd block die's with an error
  661. that is a plain string. (Unless C<$Error::ObjectifyCallback> is modified)
  662. =head1 $Error::ObjectifyCallback
  663. This variable holds a reference to a subroutine that converts errors that
  664. are plain strings to objects. It is used by Error.pm to convert textual
  665. errors to objects, and can be overrided by the user.
  666. It accepts a single argument which is a hash reference to named parameters.
  667. Currently the only named parameter passed is C<'text'> which is the text
  668. of the error, but others may be available in the future.
  669. For example the following code will cause Error.pm to throw objects of the
  670. class MyError::Bar by default:
  671. sub throw_MyError_Bar
  672. {
  673. my $args = shift;
  674. my $err = MyError::Bar->new();
  675. $err->{'MyBarText'} = $args->{'text'};
  676. return $err;
  677. }
  678. {
  679. local $Error::ObjectifyCallback = \&throw_MyError_Bar;
  680. # Error handling here.
  681. }
  682. =cut
  683. =head1 MESSAGE HANDLERS
  684. C<Error> also provides handlers to extend the output of the C<warn()> perl
  685. function, and to handle the printing of a thrown C<Error> that is not caught
  686. or otherwise handled. These are not installed by default, but are requested
  687. using the C<:warndie> tag in the C<use> line.
  688. use Error qw( :warndie );
  689. These new error handlers are installed in C<$SIG{__WARN__}> and
  690. C<$SIG{__DIE__}>. If these handlers are already defined when the tag is
  691. imported, the old values are stored, and used during the new code. Thus, to
  692. arrange for custom handling of warnings and errors, you will need to perform
  693. something like the following:
  694. BEGIN {
  695. $SIG{__WARN__} = sub {
  696. print STDERR "My special warning handler: $_[0]"
  697. };
  698. }
  699. use Error qw( :warndie );
  700. Note that setting C<$SIG{__WARN__}> after the C<:warndie> tag has been
  701. imported will overwrite the handler that C<Error> provides. If this cannot be
  702. avoided, then the tag can be explicitly C<import>ed later
  703. use Error;
  704. $SIG{__WARN__} = ...;
  705. import Error qw( :warndie );
  706. =head2 EXAMPLE
  707. The C<__DIE__> handler turns messages such as
  708. Can't call method "foo" on an undefined value at examples/warndie.pl line 16.
  709. into
  710. Unhandled perl error caught at toplevel:
  711. Can't call method "foo" on an undefined value
  712. Thrown from: examples/warndie.pl:16
  713. Full stack trace:
  714. main::inner('undef') called at examples/warndie.pl line 20
  715. main::outer('undef') called at examples/warndie.pl line 23
  716. =cut
  717. =head1 SEE ALSO
  718. See L<Exception::Class> for a different module providing Object-Oriented
  719. exception handling, along with a convenient syntax for declaring hierarchies
  720. for them. It doesn't provide Error's syntactic sugar of C<try { ... }>,
  721. C<catch { ... }>, etc. which may be a good thing or a bad thing based
  722. on what you want. (Because Error's syntactic sugar tends to break.)
  723. L<Error::Exception> aims to combine L<Error> and L<Exception::Class>
  724. "with correct stringification".
  725. =head1 KNOWN BUGS
  726. None, but that does not mean there are not any.
  727. =head1 AUTHORS
  728. Graham Barr <gbarr@pobox.com>
  729. The code that inspired me to write this was originally written by
  730. Peter Seibel <peter@weblogic.com> and adapted by Jesse Glick
  731. <jglick@sig.bsh.com>.
  732. C<:warndie> handlers added by Paul Evans <leonerd@leonerd.org.uk>
  733. =head1 MAINTAINER
  734. Shlomi Fish <shlomif@iglu.org.il>
  735. =head1 PAST MAINTAINERS
  736. Arun Kumar U <u_arunkumar@yahoo.com>
  737. =head1 COPYRIGHT
  738. Copyright (c) 1997-8 Graham Barr. All rights reserved.
  739. This program is free software; you can redistribute it and/or modify it
  740. under the same terms as Perl itself.
  741. =cut