PageRenderTime 64ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/perl/site/lib/Error.pm

http://github.com/dwimperl/perl-5.14.2.1-32bit-windows
Perl | 1035 lines | 733 code | 243 blank | 59 comment | 66 complexity | 804f0d0c076b336324b6db2589a76922 MD5 | raw file
Possible License(s): LGPL-3.0, Unlicense, GPL-2.0, LGPL-2.0, BSD-3-Clause, LGPL-2.1, AGPL-1.0, GPL-3.0
  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.17017";
  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 WARNING
  482. Using the "Error" module is B<no longer recommended> due to the black-magical
  483. nature of its syntactic sugar, which often tends to break. Its maintainers
  484. have stopped actively writing code that uses it, and discourage people
  485. from doing so. See the "SEE ALSO" section below for better recommendations.
  486. =head1 SYNOPSIS
  487. use Error qw(:try);
  488. throw Error::Simple( "A simple error");
  489. sub xyz {
  490. ...
  491. record Error::Simple("A simple error")
  492. and return;
  493. }
  494. unlink($file) or throw Error::Simple("$file: $!",$!);
  495. try {
  496. do_some_stuff();
  497. die "error!" if $condition;
  498. throw Error::Simple "Oops!" if $other_condition;
  499. }
  500. catch Error::IO with {
  501. my $E = shift;
  502. print STDERR "File ", $E->{'-file'}, " had a problem\n";
  503. }
  504. except {
  505. my $E = shift;
  506. my $general_handler=sub {send_message $E->{-description}};
  507. return {
  508. UserException1 => $general_handler,
  509. UserException2 => $general_handler
  510. };
  511. }
  512. otherwise {
  513. print STDERR "Well I don't know what to say\n";
  514. }
  515. finally {
  516. close_the_garage_door_already(); # Should be reliable
  517. }; # Don't forget the trailing ; or you might be surprised
  518. =head1 DESCRIPTION
  519. The C<Error> package provides two interfaces. Firstly C<Error> provides
  520. a procedural interface to exception handling. Secondly C<Error> is a
  521. base class for errors/exceptions that can either be thrown, for
  522. subsequent catch, or can simply be recorded.
  523. Errors in the class C<Error> should not be thrown directly, but the
  524. user should throw errors from a sub-class of C<Error>.
  525. =head1 PROCEDURAL INTERFACE
  526. C<Error> exports subroutines to perform exception handling. These will
  527. be exported if the C<:try> tag is used in the C<use> line.
  528. =over 4
  529. =item try BLOCK CLAUSES
  530. C<try> is the main subroutine called by the user. All other subroutines
  531. exported are clauses to the try subroutine.
  532. The BLOCK will be evaluated and, if no error is throw, try will return
  533. the result of the block.
  534. C<CLAUSES> are the subroutines below, which describe what to do in the
  535. event of an error being thrown within BLOCK.
  536. =item catch CLASS with BLOCK
  537. This clauses will cause all errors that satisfy C<$err-E<gt>isa(CLASS)>
  538. to be caught and handled by evaluating C<BLOCK>.
  539. C<BLOCK> will be passed two arguments. The first will be the error
  540. being thrown. The second is a reference to a scalar variable. If this
  541. variable is set by the catch block then, on return from the catch
  542. block, try will continue processing as if the catch block was never
  543. found. The error will also be available in C<$@>.
  544. To propagate the error the catch block may call C<$err-E<gt>throw>
  545. If the scalar reference by the second argument is not set, and the
  546. error is not thrown. Then the current try block will return with the
  547. result from the catch block.
  548. =item except BLOCK
  549. When C<try> is looking for a handler, if an except clause is found
  550. C<BLOCK> is evaluated. The return value from this block should be a
  551. HASHREF or a list of key-value pairs, where the keys are class names
  552. and the values are CODE references for the handler of errors of that
  553. type.
  554. =item otherwise BLOCK
  555. Catch any error by executing the code in C<BLOCK>
  556. When evaluated C<BLOCK> will be passed one argument, which will be the
  557. error being processed. The error will also be available in C<$@>.
  558. Only one otherwise block may be specified per try block
  559. =item finally BLOCK
  560. Execute the code in C<BLOCK> either after the code in the try block has
  561. successfully completed, or if the try block throws an error then
  562. C<BLOCK> will be executed after the handler has completed.
  563. If the handler throws an error then the error will be caught, the
  564. finally block will be executed and the error will be re-thrown.
  565. Only one finally block may be specified per try block
  566. =back
  567. =head1 COMPATIBILITY
  568. L<Moose> exports a keyword called C<with> which clashes with Error's. This
  569. example returns a prototype mismatch error:
  570. package MyTest;
  571. use warnings;
  572. use Moose;
  573. use Error qw(:try);
  574. (Thanks to C<maik.hentsche@amd.com> for the report.).
  575. =head1 CLASS INTERFACE
  576. =head2 CONSTRUCTORS
  577. The C<Error> object is implemented as a HASH. This HASH is initialized
  578. with the arguments that are passed to it's constructor. The elements
  579. that are used by, or are retrievable by the C<Error> class are listed
  580. below, other classes may add to these.
  581. -file
  582. -line
  583. -text
  584. -value
  585. -object
  586. If C<-file> or C<-line> are not specified in the constructor arguments
  587. then these will be initialized with the file name and line number where
  588. the constructor was called from.
  589. If the error is associated with an object then the object should be
  590. passed as the C<-object> argument. This will allow the C<Error> package
  591. to associate the error with the object.
  592. The C<Error> package remembers the last error created, and also the
  593. last error associated with a package. This could either be the last
  594. error created by a sub in that package, or the last error which passed
  595. an object blessed into that package as the C<-object> argument.
  596. =over 4
  597. =item Error->new()
  598. See the Error::Simple documentation.
  599. =item throw ( [ ARGS ] )
  600. Create a new C<Error> object and throw an error, which will be caught
  601. by a surrounding C<try> block, if there is one. Otherwise it will cause
  602. the program to exit.
  603. C<throw> may also be called on an existing error to re-throw it.
  604. =item with ( [ ARGS ] )
  605. Create a new C<Error> object and returns it. This is defined for
  606. syntactic sugar, eg
  607. die with Some::Error ( ... );
  608. =item record ( [ ARGS ] )
  609. Create a new C<Error> object and returns it. This is defined for
  610. syntactic sugar, eg
  611. record Some::Error ( ... )
  612. and return;
  613. =back
  614. =head2 STATIC METHODS
  615. =over 4
  616. =item prior ( [ PACKAGE ] )
  617. Return the last error created, or the last error associated with
  618. C<PACKAGE>
  619. =item flush ( [ PACKAGE ] )
  620. Flush the last error created, or the last error associated with
  621. C<PACKAGE>.It is necessary to clear the error stack before exiting the
  622. package or uncaught errors generated using C<record> will be reported.
  623. $Error->flush;
  624. =cut
  625. =back
  626. =head2 OBJECT METHODS
  627. =over 4
  628. =item stacktrace
  629. If the variable C<$Error::Debug> was non-zero when the error was
  630. created, then C<stacktrace> returns a string created by calling
  631. C<Carp::longmess>. If the variable was zero the C<stacktrace> returns
  632. the text of the error appended with the filename and line number of
  633. where the error was created, providing the text does not end with a
  634. newline.
  635. =item object
  636. The object this error was associated with
  637. =item file
  638. The file where the constructor of this error was called from
  639. =item line
  640. The line where the constructor of this error was called from
  641. =item text
  642. The text of the error
  643. =item $err->associate($obj)
  644. Associates an error with an object to allow error propagation. I.e:
  645. $ber->encode(...) or
  646. return Error->prior($ber)->associate($ldap);
  647. =back
  648. =head2 OVERLOAD METHODS
  649. =over 4
  650. =item stringify
  651. A method that converts the object into a string. This method may simply
  652. return the same as the C<text> method, or it may append more
  653. information. For example the file name and line number.
  654. By default this method returns the C<-text> argument that was passed to
  655. the constructor, or the string C<"Died"> if none was given.
  656. =item value
  657. A method that will return a value that can be associated with the
  658. error. For example if an error was created due to the failure of a
  659. system call, then this may return the numeric value of C<$!> at the
  660. time.
  661. By default this method returns the C<-value> argument that was passed
  662. to the constructor.
  663. =back
  664. =head1 PRE-DEFINED ERROR CLASSES
  665. =head2 Error::Simple
  666. This class can be used to hold simple error strings and values. It's
  667. constructor takes two arguments. The first is a text value, the second
  668. is a numeric value. These values are what will be returned by the
  669. overload methods.
  670. If the text value ends with C<at file line 1> as $@ strings do, then
  671. this infomation will be used to set the C<-file> and C<-line> arguments
  672. of the error object.
  673. This class is used internally if an eval'd block die's with an error
  674. that is a plain string. (Unless C<$Error::ObjectifyCallback> is modified)
  675. =head1 $Error::ObjectifyCallback
  676. This variable holds a reference to a subroutine that converts errors that
  677. are plain strings to objects. It is used by Error.pm to convert textual
  678. errors to objects, and can be overrided by the user.
  679. It accepts a single argument which is a hash reference to named parameters.
  680. Currently the only named parameter passed is C<'text'> which is the text
  681. of the error, but others may be available in the future.
  682. For example the following code will cause Error.pm to throw objects of the
  683. class MyError::Bar by default:
  684. sub throw_MyError_Bar
  685. {
  686. my $args = shift;
  687. my $err = MyError::Bar->new();
  688. $err->{'MyBarText'} = $args->{'text'};
  689. return $err;
  690. }
  691. {
  692. local $Error::ObjectifyCallback = \&throw_MyError_Bar;
  693. # Error handling here.
  694. }
  695. =cut
  696. =head1 MESSAGE HANDLERS
  697. C<Error> also provides handlers to extend the output of the C<warn()> perl
  698. function, and to handle the printing of a thrown C<Error> that is not caught
  699. or otherwise handled. These are not installed by default, but are requested
  700. using the C<:warndie> tag in the C<use> line.
  701. use Error qw( :warndie );
  702. These new error handlers are installed in C<$SIG{__WARN__}> and
  703. C<$SIG{__DIE__}>. If these handlers are already defined when the tag is
  704. imported, the old values are stored, and used during the new code. Thus, to
  705. arrange for custom handling of warnings and errors, you will need to perform
  706. something like the following:
  707. BEGIN {
  708. $SIG{__WARN__} = sub {
  709. print STDERR "My special warning handler: $_[0]"
  710. };
  711. }
  712. use Error qw( :warndie );
  713. Note that setting C<$SIG{__WARN__}> after the C<:warndie> tag has been
  714. imported will overwrite the handler that C<Error> provides. If this cannot be
  715. avoided, then the tag can be explicitly C<import>ed later
  716. use Error;
  717. $SIG{__WARN__} = ...;
  718. import Error qw( :warndie );
  719. =head2 EXAMPLE
  720. The C<__DIE__> handler turns messages such as
  721. Can't call method "foo" on an undefined value at examples/warndie.pl line 16.
  722. into
  723. Unhandled perl error caught at toplevel:
  724. Can't call method "foo" on an undefined value
  725. Thrown from: examples/warndie.pl:16
  726. Full stack trace:
  727. main::inner('undef') called at examples/warndie.pl line 20
  728. main::outer('undef') called at examples/warndie.pl line 23
  729. =cut
  730. =head1 SEE ALSO
  731. See L<Exception::Class> for a different module providing Object-Oriented
  732. exception handling, along with a convenient syntax for declaring hierarchies
  733. for them. It doesn't provide Error's syntactic sugar of C<try { ... }>,
  734. C<catch { ... }>, etc. which may be a good thing or a bad thing based
  735. on what you want. (Because Error's syntactic sugar tends to break.)
  736. L<Error::Exception> aims to combine L<Error> and L<Exception::Class>
  737. "with correct stringification".
  738. L<TryCatch> and L<Try::Tiny> are similar in concept to Error.pm only providing
  739. a syntax that hopefully breaks less.
  740. =head1 KNOWN BUGS
  741. None, but that does not mean there are not any.
  742. =head1 AUTHORS
  743. Graham Barr <gbarr@pobox.com>
  744. The code that inspired me to write this was originally written by
  745. Peter Seibel <peter@weblogic.com> and adapted by Jesse Glick
  746. <jglick@sig.bsh.com>.
  747. C<:warndie> handlers added by Paul Evans <leonerd@leonerd.org.uk>
  748. =head1 MAINTAINER
  749. Shlomi Fish <shlomif@iglu.org.il>
  750. =head1 PAST MAINTAINERS
  751. Arun Kumar U <u_arunkumar@yahoo.com>
  752. =head1 COPYRIGHT
  753. Copyright (c) 1997-8 Graham Barr. All rights reserved.
  754. This program is free software; you can redistribute it and/or modify it
  755. under the same terms as Perl itself.
  756. =cut