PageRenderTime 65ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/.metadata/.plugins/com.aptana.portablegit.win32/lib/perl5/site_perl/Error.pm

https://bitbucket.org/petersaints/pmp
Perl | 827 lines | 604 code | 164 blank | 59 comment | 49 complexity | 32902c86bbbf345a203e74b0d9bd9fb1 MD5 | raw file
Possible License(s): AGPL-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.15009";
  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. sub import {
  36. shift;
  37. local $Exporter::ExportLevel = $Exporter::ExportLevel + 1;
  38. Error::subs->import(@_);
  39. }
  40. # I really want to use last for the name of this method, but it is a keyword
  41. # which prevent the syntax last Error
  42. sub prior {
  43. shift; # ignore
  44. return $LAST unless @_;
  45. my $pkg = shift;
  46. return exists $ERROR{$pkg} ? $ERROR{$pkg} : undef
  47. unless ref($pkg);
  48. my $obj = $pkg;
  49. my $err = undef;
  50. if($obj->isa('HASH')) {
  51. $err = $obj->{'__Error__'}
  52. if exists $obj->{'__Error__'};
  53. }
  54. elsif($obj->isa('GLOB')) {
  55. $err = ${*$obj}{'__Error__'}
  56. if exists ${*$obj}{'__Error__'};
  57. }
  58. $err;
  59. }
  60. sub flush {
  61. shift; #ignore
  62. unless (@_) {
  63. $LAST = undef;
  64. return;
  65. }
  66. my $pkg = shift;
  67. return unless ref($pkg);
  68. undef $ERROR{$pkg} if defined $ERROR{$pkg};
  69. }
  70. # Return as much information as possible about where the error
  71. # happened. The -stacktrace element only exists if $Error::DEBUG
  72. # was set when the error was created
  73. sub stacktrace {
  74. my $self = shift;
  75. return $self->{'-stacktrace'}
  76. if exists $self->{'-stacktrace'};
  77. my $text = exists $self->{'-text'} ? $self->{'-text'} : "Died";
  78. $text .= sprintf(" at %s line %d.\n", $self->file, $self->line)
  79. unless($text =~ /\n$/s);
  80. $text;
  81. }
  82. # Allow error propagation, ie
  83. #
  84. # $ber->encode(...) or
  85. # return Error->prior($ber)->associate($ldap);
  86. sub associate {
  87. my $err = shift;
  88. my $obj = shift;
  89. return unless ref($obj);
  90. if($obj->isa('HASH')) {
  91. $obj->{'__Error__'} = $err;
  92. }
  93. elsif($obj->isa('GLOB')) {
  94. ${*$obj}{'__Error__'} = $err;
  95. }
  96. $obj = ref($obj);
  97. $ERROR{ ref($obj) } = $err;
  98. return;
  99. }
  100. sub new {
  101. my $self = shift;
  102. my($pkg,$file,$line) = caller($Error::Depth);
  103. my $err = bless {
  104. '-package' => $pkg,
  105. '-file' => $file,
  106. '-line' => $line,
  107. @_
  108. }, $self;
  109. $err->associate($err->{'-object'})
  110. if(exists $err->{'-object'});
  111. # To always create a stacktrace would be very inefficient, so
  112. # we only do it if $Error::Debug is set
  113. if($Error::Debug) {
  114. require Carp;
  115. local $Carp::CarpLevel = $Error::Depth;
  116. my $text = defined($err->{'-text'}) ? $err->{'-text'} : "Error";
  117. my $trace = Carp::longmess($text);
  118. # Remove try calls from the trace
  119. $trace =~ s/(\n\s+\S+__ANON__[^\n]+)?\n\s+eval[^\n]+\n\s+Error::subs::try[^\n]+(?=\n)//sog;
  120. $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;
  121. $err->{'-stacktrace'} = $trace
  122. }
  123. $@ = $LAST = $ERROR{$pkg} = $err;
  124. }
  125. # Throw an error. this contains some very gory code.
  126. sub throw {
  127. my $self = shift;
  128. local $Error::Depth = $Error::Depth + 1;
  129. # if we are not rethrow-ing then create the object to throw
  130. $self = $self->new(@_) unless ref($self);
  131. die $Error::THROWN = $self;
  132. }
  133. # syntactic sugar for
  134. #
  135. # die with Error( ... );
  136. sub with {
  137. my $self = shift;
  138. local $Error::Depth = $Error::Depth + 1;
  139. $self->new(@_);
  140. }
  141. # syntactic sugar for
  142. #
  143. # record Error( ... ) and return;
  144. sub record {
  145. my $self = shift;
  146. local $Error::Depth = $Error::Depth + 1;
  147. $self->new(@_);
  148. }
  149. # catch clause for
  150. #
  151. # try { ... } catch CLASS with { ... }
  152. sub catch {
  153. my $pkg = shift;
  154. my $code = shift;
  155. my $clauses = shift || {};
  156. my $catch = $clauses->{'catch'} ||= [];
  157. unshift @$catch, $pkg, $code;
  158. $clauses;
  159. }
  160. # Object query methods
  161. sub object {
  162. my $self = shift;
  163. exists $self->{'-object'} ? $self->{'-object'} : undef;
  164. }
  165. sub file {
  166. my $self = shift;
  167. exists $self->{'-file'} ? $self->{'-file'} : undef;
  168. }
  169. sub line {
  170. my $self = shift;
  171. exists $self->{'-line'} ? $self->{'-line'} : undef;
  172. }
  173. sub text {
  174. my $self = shift;
  175. exists $self->{'-text'} ? $self->{'-text'} : undef;
  176. }
  177. # overload methods
  178. sub stringify {
  179. my $self = shift;
  180. defined $self->{'-text'} ? $self->{'-text'} : "Died";
  181. }
  182. sub value {
  183. my $self = shift;
  184. exists $self->{'-value'} ? $self->{'-value'} : undef;
  185. }
  186. package Error::Simple;
  187. @Error::Simple::ISA = qw(Error);
  188. sub new {
  189. my $self = shift;
  190. my $text = "" . shift;
  191. my $value = shift;
  192. my(@args) = ();
  193. local $Error::Depth = $Error::Depth + 1;
  194. @args = ( -file => $1, -line => $2)
  195. if($text =~ s/\s+at\s+(\S+)\s+line\s+(\d+)(?:,\s*<[^>]*>\s+line\s+\d+)?\.?\n?$//s);
  196. push(@args, '-value', 0 + $value)
  197. if defined($value);
  198. $self->SUPER::new(-text => $text, @args);
  199. }
  200. sub stringify {
  201. my $self = shift;
  202. my $text = $self->SUPER::stringify;
  203. $text .= sprintf(" at %s line %d.\n", $self->file, $self->line)
  204. unless($text =~ /\n$/s);
  205. $text;
  206. }
  207. ##########################################################################
  208. ##########################################################################
  209. # Inspired by code from Jesse Glick <jglick@sig.bsh.com> and
  210. # Peter Seibel <peter@weblogic.com>
  211. package Error::subs;
  212. use Exporter ();
  213. use vars qw(@EXPORT_OK @ISA %EXPORT_TAGS);
  214. @EXPORT_OK = qw(try with finally except otherwise);
  215. %EXPORT_TAGS = (try => \@EXPORT_OK);
  216. @ISA = qw(Exporter);
  217. sub blessed {
  218. my $item = shift;
  219. local $@; # don't kill an outer $@
  220. ref $item and eval { $item->can('can') };
  221. }
  222. sub run_clauses ($$$\@) {
  223. my($clauses,$err,$wantarray,$result) = @_;
  224. my $code = undef;
  225. $err = $Error::ObjectifyCallback->({'text' =>$err}) unless ref($err);
  226. CATCH: {
  227. # catch
  228. my $catch;
  229. if(defined($catch = $clauses->{'catch'})) {
  230. my $i = 0;
  231. CATCHLOOP:
  232. for( ; $i < @$catch ; $i += 2) {
  233. my $pkg = $catch->[$i];
  234. unless(defined $pkg) {
  235. #except
  236. splice(@$catch,$i,2,$catch->[$i+1]->());
  237. $i -= 2;
  238. next CATCHLOOP;
  239. }
  240. elsif(blessed($err) && $err->isa($pkg)) {
  241. $code = $catch->[$i+1];
  242. while(1) {
  243. my $more = 0;
  244. local($Error::THROWN);
  245. my $ok = eval {
  246. if($wantarray) {
  247. @{$result} = $code->($err,\$more);
  248. }
  249. elsif(defined($wantarray)) {
  250. @{$result} = ();
  251. $result->[0] = $code->($err,\$more);
  252. }
  253. else {
  254. $code->($err,\$more);
  255. }
  256. 1;
  257. };
  258. if( $ok ) {
  259. next CATCHLOOP if $more;
  260. undef $err;
  261. }
  262. else {
  263. $err = defined($Error::THROWN)
  264. ? $Error::THROWN : $@;
  265. $err = $Error::ObjectifyCallback->({'text' =>$err})
  266. unless ref($err);
  267. }
  268. last CATCH;
  269. };
  270. }
  271. }
  272. }
  273. # otherwise
  274. my $owise;
  275. if(defined($owise = $clauses->{'otherwise'})) {
  276. my $code = $clauses->{'otherwise'};
  277. my $more = 0;
  278. my $ok = eval {
  279. if($wantarray) {
  280. @{$result} = $code->($err,\$more);
  281. }
  282. elsif(defined($wantarray)) {
  283. @{$result} = ();
  284. $result->[0] = $code->($err,\$more);
  285. }
  286. else {
  287. $code->($err,\$more);
  288. }
  289. 1;
  290. };
  291. if( $ok ) {
  292. undef $err;
  293. }
  294. else {
  295. $err = defined($Error::THROWN)
  296. ? $Error::THROWN : $@;
  297. $err = $Error::ObjectifyCallback->({'text' =>$err})
  298. unless ref($err);
  299. }
  300. }
  301. }
  302. $err;
  303. }
  304. sub try (&;$) {
  305. my $try = shift;
  306. my $clauses = @_ ? shift : {};
  307. my $ok = 0;
  308. my $err = undef;
  309. my @result = ();
  310. unshift @Error::STACK, $clauses;
  311. my $wantarray = wantarray();
  312. do {
  313. local $Error::THROWN = undef;
  314. local $@ = undef;
  315. $ok = eval {
  316. if($wantarray) {
  317. @result = $try->();
  318. }
  319. elsif(defined $wantarray) {
  320. $result[0] = $try->();
  321. }
  322. else {
  323. $try->();
  324. }
  325. 1;
  326. };
  327. $err = defined($Error::THROWN) ? $Error::THROWN : $@
  328. unless $ok;
  329. };
  330. shift @Error::STACK;
  331. $err = run_clauses($clauses,$err,wantarray,@result)
  332. unless($ok);
  333. $clauses->{'finally'}->()
  334. if(defined($clauses->{'finally'}));
  335. if (defined($err))
  336. {
  337. if (blessed($err) && $err->can('throw'))
  338. {
  339. throw $err;
  340. }
  341. else
  342. {
  343. die $err;
  344. }
  345. }
  346. wantarray ? @result : $result[0];
  347. }
  348. # Each clause adds a sub to the list of clauses. The finally clause is
  349. # always the last, and the otherwise clause is always added just before
  350. # the finally clause.
  351. #
  352. # All clauses, except the finally clause, add a sub which takes one argument
  353. # this argument will be the error being thrown. The sub will return a code ref
  354. # if that clause can handle that error, otherwise undef is returned.
  355. #
  356. # The otherwise clause adds a sub which unconditionally returns the users
  357. # code reference, this is why it is forced to be last.
  358. #
  359. # The catch clause is defined in Error.pm, as the syntax causes it to
  360. # be called as a method
  361. sub with (&;$) {
  362. @_
  363. }
  364. sub finally (&) {
  365. my $code = shift;
  366. my $clauses = { 'finally' => $code };
  367. $clauses;
  368. }
  369. # The except clause is a block which returns a hashref or a list of
  370. # key-value pairs, where the keys are the classes and the values are subs.
  371. sub except (&;$) {
  372. my $code = shift;
  373. my $clauses = shift || {};
  374. my $catch = $clauses->{'catch'} ||= [];
  375. my $sub = sub {
  376. my $ref;
  377. my(@array) = $code->($_[0]);
  378. if(@array == 1 && ref($array[0])) {
  379. $ref = $array[0];
  380. $ref = [ %$ref ]
  381. if(UNIVERSAL::isa($ref,'HASH'));
  382. }
  383. else {
  384. $ref = \@array;
  385. }
  386. @$ref
  387. };
  388. unshift @{$catch}, undef, $sub;
  389. $clauses;
  390. }
  391. sub otherwise (&;$) {
  392. my $code = shift;
  393. my $clauses = shift || {};
  394. if(exists $clauses->{'otherwise'}) {
  395. require Carp;
  396. Carp::croak("Multiple otherwise clauses");
  397. }
  398. $clauses->{'otherwise'} = $code;
  399. $clauses;
  400. }
  401. 1;
  402. __END__
  403. =head1 NAME
  404. Error - Error/exception handling in an OO-ish way
  405. =head1 SYNOPSIS
  406. use Error qw(:try);
  407. throw Error::Simple( "A simple error");
  408. sub xyz {
  409. ...
  410. record Error::Simple("A simple error")
  411. and return;
  412. }
  413. unlink($file) or throw Error::Simple("$file: $!",$!);
  414. try {
  415. do_some_stuff();
  416. die "error!" if $condition;
  417. throw Error::Simple -text => "Oops!" if $other_condition;
  418. }
  419. catch Error::IO with {
  420. my $E = shift;
  421. print STDERR "File ", $E->{'-file'}, " had a problem\n";
  422. }
  423. except {
  424. my $E = shift;
  425. my $general_handler=sub {send_message $E->{-description}};
  426. return {
  427. UserException1 => $general_handler,
  428. UserException2 => $general_handler
  429. };
  430. }
  431. otherwise {
  432. print STDERR "Well I don't know what to say\n";
  433. }
  434. finally {
  435. close_the_garage_door_already(); # Should be reliable
  436. }; # Don't forget the trailing ; or you might be surprised
  437. =head1 DESCRIPTION
  438. The C<Error> package provides two interfaces. Firstly C<Error> provides
  439. a procedural interface to exception handling. Secondly C<Error> is a
  440. base class for errors/exceptions that can either be thrown, for
  441. subsequent catch, or can simply be recorded.
  442. Errors in the class C<Error> should not be thrown directly, but the
  443. user should throw errors from a sub-class of C<Error>.
  444. =head1 PROCEDURAL INTERFACE
  445. C<Error> exports subroutines to perform exception handling. These will
  446. be exported if the C<:try> tag is used in the C<use> line.
  447. =over 4
  448. =item try BLOCK CLAUSES
  449. C<try> is the main subroutine called by the user. All other subroutines
  450. exported are clauses to the try subroutine.
  451. The BLOCK will be evaluated and, if no error is throw, try will return
  452. the result of the block.
  453. C<CLAUSES> are the subroutines below, which describe what to do in the
  454. event of an error being thrown within BLOCK.
  455. =item catch CLASS with BLOCK
  456. This clauses will cause all errors that satisfy C<$err-E<gt>isa(CLASS)>
  457. to be caught and handled by evaluating C<BLOCK>.
  458. C<BLOCK> will be passed two arguments. The first will be the error
  459. being thrown. The second is a reference to a scalar variable. If this
  460. variable is set by the catch block then, on return from the catch
  461. block, try will continue processing as if the catch block was never
  462. found.
  463. To propagate the error the catch block may call C<$err-E<gt>throw>
  464. If the scalar reference by the second argument is not set, and the
  465. error is not thrown. Then the current try block will return with the
  466. result from the catch block.
  467. =item except BLOCK
  468. When C<try> is looking for a handler, if an except clause is found
  469. C<BLOCK> is evaluated. The return value from this block should be a
  470. HASHREF or a list of key-value pairs, where the keys are class names
  471. and the values are CODE references for the handler of errors of that
  472. type.
  473. =item otherwise BLOCK
  474. Catch any error by executing the code in C<BLOCK>
  475. When evaluated C<BLOCK> will be passed one argument, which will be the
  476. error being processed.
  477. Only one otherwise block may be specified per try block
  478. =item finally BLOCK
  479. Execute the code in C<BLOCK> either after the code in the try block has
  480. successfully completed, or if the try block throws an error then
  481. C<BLOCK> will be executed after the handler has completed.
  482. If the handler throws an error then the error will be caught, the
  483. finally block will be executed and the error will be re-thrown.
  484. Only one finally block may be specified per try block
  485. =back
  486. =head1 CLASS INTERFACE
  487. =head2 CONSTRUCTORS
  488. The C<Error> object is implemented as a HASH. This HASH is initialized
  489. with the arguments that are passed to it's constructor. The elements
  490. that are used by, or are retrievable by the C<Error> class are listed
  491. below, other classes may add to these.
  492. -file
  493. -line
  494. -text
  495. -value
  496. -object
  497. If C<-file> or C<-line> are not specified in the constructor arguments
  498. then these will be initialized with the file name and line number where
  499. the constructor was called from.
  500. If the error is associated with an object then the object should be
  501. passed as the C<-object> argument. This will allow the C<Error> package
  502. to associate the error with the object.
  503. The C<Error> package remembers the last error created, and also the
  504. last error associated with a package. This could either be the last
  505. error created by a sub in that package, or the last error which passed
  506. an object blessed into that package as the C<-object> argument.
  507. =over 4
  508. =item throw ( [ ARGS ] )
  509. Create a new C<Error> object and throw an error, which will be caught
  510. by a surrounding C<try> block, if there is one. Otherwise it will cause
  511. the program to exit.
  512. C<throw> may also be called on an existing error to re-throw it.
  513. =item with ( [ ARGS ] )
  514. Create a new C<Error> object and returns it. This is defined for
  515. syntactic sugar, eg
  516. die with Some::Error ( ... );
  517. =item record ( [ ARGS ] )
  518. Create a new C<Error> object and returns it. This is defined for
  519. syntactic sugar, eg
  520. record Some::Error ( ... )
  521. and return;
  522. =back
  523. =head2 STATIC METHODS
  524. =over 4
  525. =item prior ( [ PACKAGE ] )
  526. Return the last error created, or the last error associated with
  527. C<PACKAGE>
  528. =item flush ( [ PACKAGE ] )
  529. Flush the last error created, or the last error associated with
  530. C<PACKAGE>.It is necessary to clear the error stack before exiting the
  531. package or uncaught errors generated using C<record> will be reported.
  532. $Error->flush;
  533. =cut
  534. =back
  535. =head2 OBJECT METHODS
  536. =over 4
  537. =item stacktrace
  538. If the variable C<$Error::Debug> was non-zero when the error was
  539. created, then C<stacktrace> returns a string created by calling
  540. C<Carp::longmess>. If the variable was zero the C<stacktrace> returns
  541. the text of the error appended with the filename and line number of
  542. where the error was created, providing the text does not end with a
  543. newline.
  544. =item object
  545. The object this error was associated with
  546. =item file
  547. The file where the constructor of this error was called from
  548. =item line
  549. The line where the constructor of this error was called from
  550. =item text
  551. The text of the error
  552. =back
  553. =head2 OVERLOAD METHODS
  554. =over 4
  555. =item stringify
  556. A method that converts the object into a string. This method may simply
  557. return the same as the C<text> method, or it may append more
  558. information. For example the file name and line number.
  559. By default this method returns the C<-text> argument that was passed to
  560. the constructor, or the string C<"Died"> if none was given.
  561. =item value
  562. A method that will return a value that can be associated with the
  563. error. For example if an error was created due to the failure of a
  564. system call, then this may return the numeric value of C<$!> at the
  565. time.
  566. By default this method returns the C<-value> argument that was passed
  567. to the constructor.
  568. =back
  569. =head1 PRE-DEFINED ERROR CLASSES
  570. =over 4
  571. =item Error::Simple
  572. This class can be used to hold simple error strings and values. It's
  573. constructor takes two arguments. The first is a text value, the second
  574. is a numeric value. These values are what will be returned by the
  575. overload methods.
  576. If the text value ends with C<at file line 1> as $@ strings do, then
  577. this infomation will be used to set the C<-file> and C<-line> arguments
  578. of the error object.
  579. This class is used internally if an eval'd block die's with an error
  580. that is a plain string. (Unless C<$Error::ObjectifyCallback> is modified)
  581. =back
  582. =head1 $Error::ObjectifyCallback
  583. This variable holds a reference to a subroutine that converts errors that
  584. are plain strings to objects. It is used by Error.pm to convert textual
  585. errors to objects, and can be overridden by the user.
  586. It accepts a single argument which is a hash reference to named parameters.
  587. Currently the only named parameter passed is C<'text'> which is the text
  588. of the error, but others may be available in the future.
  589. For example the following code will cause Error.pm to throw objects of the
  590. class MyError::Bar by default:
  591. sub throw_MyError_Bar
  592. {
  593. my $args = shift;
  594. my $err = MyError::Bar->new();
  595. $err->{'MyBarText'} = $args->{'text'};
  596. return $err;
  597. }
  598. {
  599. local $Error::ObjectifyCallback = \&throw_MyError_Bar;
  600. # Error handling here.
  601. }
  602. =head1 KNOWN BUGS
  603. None, but that does not mean there are not any.
  604. =head1 AUTHORS
  605. Graham Barr <gbarr@pobox.com>
  606. The code that inspired me to write this was originally written by
  607. Peter Seibel <peter@weblogic.com> and adapted by Jesse Glick
  608. <jglick@sig.bsh.com>.
  609. =head1 MAINTAINER
  610. Shlomi Fish <shlomif@iglu.org.il>
  611. =head1 PAST MAINTAINERS
  612. Arun Kumar U <u_arunkumar@yahoo.com>
  613. =cut