1Error(3) User Contributed Perl Documentation Error(3)
2
3
4
6 Error - Error/exception handling in an OO-ish way
7
9 version 0.17029
10
12 use Error qw(:try);
13
14 throw Error::Simple( "A simple error");
15
16 sub xyz {
17 ...
18 record Error::Simple("A simple error")
19 and return;
20 }
21
22 unlink($file) or throw Error::Simple("$file: $!",$!);
23
24 try {
25 do_some_stuff();
26 die "error!" if $condition;
27 throw Error::Simple "Oops!" if $other_condition;
28 }
29 catch Error::IO with {
30 my $E = shift;
31 print STDERR "File ", $E->{'-file'}, " had a problem\n";
32 }
33 except {
34 my $E = shift;
35 my $general_handler=sub {send_message $E->{-description}};
36 return {
37 UserException1 => $general_handler,
38 UserException2 => $general_handler
39 };
40 }
41 otherwise {
42 print STDERR "Well I don't know what to say\n";
43 }
44 finally {
45 close_the_garage_door_already(); # Should be reliable
46 }; # Don't forget the trailing ; or you might be surprised
47
49 The "Error" package provides two interfaces. Firstly "Error" provides a
50 procedural interface to exception handling. Secondly "Error" is a base
51 class for errors/exceptions that can either be thrown, for subsequent
52 catch, or can simply be recorded.
53
54 Errors in the class "Error" should not be thrown directly, but the user
55 should throw errors from a sub-class of "Error".
56
58 Using the "Error" module is no longer recommended due to the black-
59 magical nature of its syntactic sugar, which often tends to break. Its
60 maintainers have stopped actively writing code that uses it, and
61 discourage people from doing so. See the "SEE ALSO" section below for
62 better recommendations.
63
65 "Error" exports subroutines to perform exception handling. These will
66 be exported if the ":try" tag is used in the "use" line.
67
68 try BLOCK CLAUSES
69 "try" is the main subroutine called by the user. All other
70 subroutines exported are clauses to the try subroutine.
71
72 The BLOCK will be evaluated and, if no error is throw, try will
73 return the result of the block.
74
75 "CLAUSES" are the subroutines below, which describe what to do in
76 the event of an error being thrown within BLOCK.
77
78 catch CLASS with BLOCK
79 This clauses will cause all errors that satisfy "$err->isa(CLASS)"
80 to be caught and handled by evaluating "BLOCK".
81
82 "BLOCK" will be passed two arguments. The first will be the error
83 being thrown. The second is a reference to a scalar variable. If
84 this variable is set by the catch block then, on return from the
85 catch block, try will continue processing as if the catch block was
86 never found. The error will also be available in $@.
87
88 To propagate the error the catch block may call "$err->throw"
89
90 If the scalar reference by the second argument is not set, and the
91 error is not thrown. Then the current try block will return with
92 the result from the catch block.
93
94 except BLOCK
95 When "try" is looking for a handler, if an except clause is found
96 "BLOCK" is evaluated. The return value from this block should be a
97 HASHREF or a list of key-value pairs, where the keys are class
98 names and the values are CODE references for the handler of errors
99 of that type.
100
101 otherwise BLOCK
102 Catch any error by executing the code in "BLOCK"
103
104 When evaluated "BLOCK" will be passed one argument, which will be
105 the error being processed. The error will also be available in $@.
106
107 Only one otherwise block may be specified per try block
108
109 finally BLOCK
110 Execute the code in "BLOCK" either after the code in the try block
111 has successfully completed, or if the try block throws an error
112 then "BLOCK" will be executed after the handler has completed.
113
114 If the handler throws an error then the error will be caught, the
115 finally block will be executed and the error will be re-thrown.
116
117 Only one finally block may be specified per try block
118
120 Moose exports a keyword called "with" which clashes with Error's. This
121 example returns a prototype mismatch error:
122
123 package MyTest;
124
125 use warnings;
126 use Moose;
127 use Error qw(:try);
128
129 (Thanks to "maik.hentsche@amd.com" for the report.).
130
132 CONSTRUCTORS
133 The "Error" object is implemented as a HASH. This HASH is initialized
134 with the arguments that are passed to it's constructor. The elements
135 that are used by, or are retrievable by the "Error" class are listed
136 below, other classes may add to these.
137
138 -file
139 -line
140 -text
141 -value
142 -object
143
144 If "-file" or "-line" are not specified in the constructor arguments
145 then these will be initialized with the file name and line number where
146 the constructor was called from.
147
148 If the error is associated with an object then the object should be
149 passed as the "-object" argument. This will allow the "Error" package
150 to associate the error with the object.
151
152 The "Error" package remembers the last error created, and also the last
153 error associated with a package. This could either be the last error
154 created by a sub in that package, or the last error which passed an
155 object blessed into that package as the "-object" argument.
156
157 Error->new()
158 See the Error::Simple documentation.
159
160 throw ( [ ARGS ] )
161 Create a new "Error" object and throw an error, which will be
162 caught by a surrounding "try" block, if there is one. Otherwise it
163 will cause the program to exit.
164
165 "throw" may also be called on an existing error to re-throw it.
166
167 with ( [ ARGS ] )
168 Create a new "Error" object and returns it. This is defined for
169 syntactic sugar, eg
170
171 die with Some::Error ( ... );
172
173 record ( [ ARGS ] )
174 Create a new "Error" object and returns it. This is defined for
175 syntactic sugar, eg
176
177 record Some::Error ( ... )
178 and return;
179
180 STATIC METHODS
181 prior ( [ PACKAGE ] )
182 Return the last error created, or the last error associated with
183 "PACKAGE"
184
185 flush ( [ PACKAGE ] )
186 Flush the last error created, or the last error associated with
187 "PACKAGE".It is necessary to clear the error stack before exiting
188 the package or uncaught errors generated using "record" will be
189 reported.
190
191 $Error->flush;
192
193 OBJECT METHODS
194 stacktrace
195 If the variable $Error::Debug was non-zero when the error was
196 created, then "stacktrace" returns a string created by calling
197 "Carp::longmess". If the variable was zero the "stacktrace" returns
198 the text of the error appended with the filename and line number of
199 where the error was created, providing the text does not end with a
200 newline.
201
202 object
203 The object this error was associated with
204
205 file
206 The file where the constructor of this error was called from
207
208 line
209 The line where the constructor of this error was called from
210
211 text
212 The text of the error
213
214 $err->associate($obj)
215 Associates an error with an object to allow error propagation. I.e:
216
217 $ber->encode(...) or
218 return Error->prior($ber)->associate($ldap);
219
220 OVERLOAD METHODS
221 stringify
222 A method that converts the object into a string. This method may
223 simply return the same as the "text" method, or it may append more
224 information. For example the file name and line number.
225
226 By default this method returns the "-text" argument that was passed
227 to the constructor, or the string "Died" if none was given.
228
229 value
230 A method that will return a value that can be associated with the
231 error. For example if an error was created due to the failure of a
232 system call, then this may return the numeric value of $! at the
233 time.
234
235 By default this method returns the "-value" argument that was
236 passed to the constructor.
237
239 Error::Simple
240 This class can be used to hold simple error strings and values. It's
241 constructor takes two arguments. The first is a text value, the second
242 is a numeric value. These values are what will be returned by the
243 overload methods.
244
245 If the text value ends with "at file line 1" as $@ strings do, then
246 this information will be used to set the "-file" and "-line" arguments
247 of the error object.
248
249 This class is used internally if an eval'd block die's with an error
250 that is a plain string. (Unless $Error::ObjectifyCallback is modified)
251
253 This variable holds a reference to a subroutine that converts errors
254 that are plain strings to objects. It is used by Error.pm to convert
255 textual errors to objects, and can be overridden by the user.
256
257 It accepts a single argument which is a hash reference to named
258 parameters. Currently the only named parameter passed is 'text' which
259 is the text of the error, but others may be available in the future.
260
261 For example the following code will cause Error.pm to throw objects of
262 the class MyError::Bar by default:
263
264 sub throw_MyError_Bar
265 {
266 my $args = shift;
267 my $err = MyError::Bar->new();
268 $err->{'MyBarText'} = $args->{'text'};
269 return $err;
270 }
271
272 {
273 local $Error::ObjectifyCallback = \&throw_MyError_Bar;
274
275 # Error handling here.
276 }
277
279 "Error" also provides handlers to extend the output of the "warn()"
280 perl function, and to handle the printing of a thrown "Error" that is
281 not caught or otherwise handled. These are not installed by default,
282 but are requested using the ":warndie" tag in the "use" line.
283
284 use Error qw( :warndie );
285
286 These new error handlers are installed in $SIG{__WARN__} and
287 $SIG{__DIE__}. If these handlers are already defined when the tag is
288 imported, the old values are stored, and used during the new code.
289 Thus, to arrange for custom handling of warnings and errors, you will
290 need to perform something like the following:
291
292 BEGIN {
293 $SIG{__WARN__} = sub {
294 print STDERR "My special warning handler: $_[0]"
295 };
296 }
297
298 use Error qw( :warndie );
299
300 Note that setting $SIG{__WARN__} after the ":warndie" tag has been
301 imported will overwrite the handler that "Error" provides. If this
302 cannot be avoided, then the tag can be explicitly "import"ed later
303
304 use Error;
305
306 $SIG{__WARN__} = ...;
307
308 import Error qw( :warndie );
309
310 EXAMPLE
311 The "__DIE__" handler turns messages such as
312
313 Can't call method "foo" on an undefined value at examples/warndie.pl line 16.
314
315 into
316
317 Unhandled perl error caught at toplevel:
318
319 Can't call method "foo" on an undefined value
320
321 Thrown from: examples/warndie.pl:16
322
323 Full stack trace:
324
325 main::inner('undef') called at examples/warndie.pl line 20
326 main::outer('undef') called at examples/warndie.pl line 23
327
329 See Exception::Class for a different module providing Object-Oriented
330 exception handling, along with a convenient syntax for declaring
331 hierarchies for them. It doesn't provide Error's syntactic sugar of
332 "try { ... }", "catch { ... }", etc. which may be a good thing or a bad
333 thing based on what you want. (Because Error's syntactic sugar tends to
334 break.)
335
336 Error::Exception aims to combine Error and Exception::Class "with
337 correct stringification".
338
339 TryCatch and Try::Tiny are similar in concept to Error.pm only
340 providing a syntax that hopefully breaks less.
341
343 None, but that does not mean there are not any.
344
346 Graham Barr <gbarr@pobox.com>
347
348 The code that inspired me to write this was originally written by Peter
349 Seibel <peter@weblogic.com> and adapted by Jesse Glick
350 <jglick@sig.bsh.com>.
351
352 ":warndie" handlers added by Paul Evans <leonerd@leonerd.org.uk>
353
355 Shlomi Fish, <http://www.shlomifish.org/> .
356
358 Arun Kumar U <u_arunkumar@yahoo.com>
359
361 Copyright (c) 1997-8 Graham Barr. All rights reserved. This program
362 is free software; you can redistribute it and/or modify it under the
363 same terms as Perl itself.
364
366 Websites
367 The following websites have more information about this module, and may
368 be of help to you. As always, in addition to those websites please use
369 your favorite search engine to discover more resources.
370
371 · MetaCPAN
372
373 A modern, open-source CPAN search engine, useful to view POD in
374 HTML format.
375
376 <https://metacpan.org/release/Error>
377
378 · Search CPAN
379
380 The default CPAN search engine, useful to view POD in HTML format.
381
382 <http://search.cpan.org/dist/Error>
383
384 · RT: CPAN's Bug Tracker
385
386 The RT ( Request Tracker ) website is the default bug/issue
387 tracking system for CPAN.
388
389 <https://rt.cpan.org/Public/Dist/Display.html?Name=Error>
390
391 · CPAN Ratings
392
393 The CPAN Ratings is a website that allows community ratings and
394 reviews of Perl modules.
395
396 <http://cpanratings.perl.org/d/Error>
397
398 · CPANTS
399
400 The CPANTS is a website that analyzes the Kwalitee ( code metrics )
401 of a distribution.
402
403 <http://cpants.cpanauthors.org/dist/Error>
404
405 · CPAN Testers
406
407 The CPAN Testers is a network of smoke testers who run automated
408 tests on uploaded CPAN distributions.
409
410 <http://www.cpantesters.org/distro/E/Error>
411
412 · CPAN Testers Matrix
413
414 The CPAN Testers Matrix is a website that provides a visual
415 overview of the test results for a distribution on various
416 Perls/platforms.
417
418 <http://matrix.cpantesters.org/?dist=Error>
419
420 · CPAN Testers Dependencies
421
422 The CPAN Testers Dependencies is a website that shows a chart of
423 the test results of all dependencies for a distribution.
424
425 <http://deps.cpantesters.org/?module=Error>
426
427 Bugs / Feature Requests
428 Please report any bugs or feature requests by email to "bug-error at
429 rt.cpan.org", or through the web interface at
430 <https://rt.cpan.org/Public/Bug/Report.html?Queue=Error>. You will be
431 automatically notified of any progress on the request by the system.
432
433 Source Code
434 The code is open to the world, and available for you to hack on. Please
435 feel free to browse it and play with it, or whatever. If you want to
436 contribute patches, please send me a diff or prod me to pull from your
437 repository :)
438
439 <https://github.com/shlomif/perl-error.pm>
440
441 git clone git://github.com/shlomif/perl-error.pm.git
442
444 Shlomi Fish ( http://www.shlomifish.org/ )
445
447 Please report any bugs or feature requests on the bugtracker website
448 <https://github.com/shlomif/perl-error.pm/issues>
449
450 When submitting a bug or request, please include a test-file or a patch
451 to an existing test-file that illustrates the bug or desired feature.
452
454 This software is copyright (c) 2020 by Shlomi Fish (
455 http://www.shlomifish.org/ ).
456
457 This is free software; you can redistribute it and/or modify it under
458 the same terms as the Perl 5 programming language system itself.
459
460
461
462perl v5.32.0 2020-07-28 Error(3)