failures-0.003/000755 000765 000024 00000000000 12263033624 013561 5ustar00davidstaff000000 000000 failures-0.003/Changes000644 000765 000024 00000001002 12263033624 015045 0ustar00davidstaff000000 000000 Revision history for failures 0.003 2014-01-07 12:21:20 America/New_York [CHANGES] - Revised default error message slightly ("Caught $class error" to "Caught $class") - Documented attributes and stringification better 0.002 2013-09-24 12:53:37 America/New_York [FIXED] - made tests less sensitive to exact short/longmess format from Carp - suppressed undef warning from length($msg) on older perls 0.001 2013-09-18 18:20:05 America/New_York - First release failures-0.003/CONTRIBUTING000644 000765 000024 00000004234 12263033624 015416 0ustar00davidstaff000000 000000 ## HOW TO CONTRIBUTE Thank you for considering contributing to this distribution. This file contains instructions that will help you work with the source code. The distribution is managed with Dist::Zilla. This means than many of the usual files you might expect are not in the repository, but are generated at release time (e.g. Makefile.PL). ### Getting dependencies See the included `cpanfile` file for a list of dependencies. If you have App::cpanminus 1.6 or later installed, you can use `cpanm` to satisfy dependencies like this: $ cpanm --installdeps . Otherwise, you can install Module::CPANfile 1.0002 or later and then satisfy dependencies with the regular `cpan` client and `cpanfile-dump`: $ cpan `cpanfile-dump` ### Running tests You can run tests directly using the `prove` tool: $ prove -l $ prove -lv t/some_test_file.t For most distributions, `prove` is entirely sufficent for you to test any patches you have. ### Code style and tidying Please try to match any existing coding style. If there is a `.perltidyrc` file, please install Perl::Tidy and use perltidy before submitting patches. If there is a `tidyall.ini` file, you can also install Code::TidyAll and run `tidyall` on a file or `tidyall -a` to tidy all files. ### Patching documentation Much of the documentation Pod is generated at release time. Depending on the distribution, some documentation may be written in a Pod dialect called WikiDoc. (See Pod::WikiDoc on CPAN.) If you would like to submit a documentation edit, please limit yourself to the documentation you see. If you see typos or documentation issues in the generated docs, please email or open a bug ticket instead of patching. ### Learning Dist::Zilla Dist::Zilla is a very powerful authoring tool, but requires a number of author-specific plugins. If you would like to use it for contributing, install it from CPAN, then run one of the following commands, depending on your CPAN client: $ cpan `dzil authordeps` $ dzil authordeps | cpanm Once installed, here are some dzil commands you might try: $ dzil build $ dzil test $ dzil xtest You can learn more about Dist::Zilla at http://dzil.org/ failures-0.003/cpanfile000644 000765 000024 00000002255 12263033624 015271 0ustar00davidstaff000000 000000 requires "Carp" => "0"; requires "Class::Tiny" => "0"; requires "overload" => "0"; requires "parent" => "0"; requires "perl" => "5.008001"; requires "strict" => "0"; requires "warnings" => "0"; on 'test' => sub { requires "Exporter" => "0"; requires "ExtUtils::MakeMaker" => "0"; requires "File::Spec::Functions" => "0"; requires "List::Util" => "0"; requires "Test::More" => "0.96"; requires "lib" => "0"; }; on 'test' => sub { recommends "CPAN::Meta" => "0"; recommends "CPAN::Meta::Requirements" => "0"; recommends "Test::FailWarnings" => "0.007"; }; on 'configure' => sub { requires "ExtUtils::MakeMaker" => "6.17"; }; on 'develop' => sub { requires "Dist::Zilla" => "5.008"; requires "Dist::Zilla::Plugin::Prereqs" => "0"; requires "Dist::Zilla::Plugin::RemovePrereqs" => "0"; requires "Dist::Zilla::PluginBundle::DAGOLDEN" => "0.053"; requires "File::Spec" => "0"; requires "File::Temp" => "0"; requires "IO::Handle" => "0"; requires "IPC::Open3" => "0"; requires "Pod::Coverage::TrustPod" => "0"; requires "Test::CPAN::Meta" => "0"; requires "Test::More" => "0"; requires "Test::Pod" => "1.41"; requires "Test::Pod::Coverage" => "1.08"; }; failures-0.003/dist.ini000644 000765 000024 00000000467 12263033624 015234 0ustar00davidstaff000000 000000 name = failures author = David Golden license = Apache_2_0 copyright_holder = David Golden copyright_year = 2013 [@DAGOLDEN] :version = 0.053 stopwords = rethrow stopwords = Throwable [RemovePrereqs] remove = Test::FailWarnings [Prereqs / TestRecommends] Test::FailWarnings = 0.007 failures-0.003/lib/000755 000765 000024 00000000000 12263033624 014327 5ustar00davidstaff000000 000000 failures-0.003/LICENSE000644 000765 000024 00000026354 12263033624 014600 0ustar00davidstaff000000 000000 This software is Copyright (c) 2013 by David Golden. This is free software, licensed under: The Apache License, Version 2.0, January 2004 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. failures-0.003/Makefile.PL000644 000765 000024 00000002742 12263033624 015540 0ustar00davidstaff000000 000000 # This file was automatically generated by Dist::Zilla::Plugin::MakeMaker v5.008. use strict; use warnings; use 5.008001; use ExtUtils::MakeMaker 6.17; my %WriteMakefileArgs = ( "ABSTRACT" => "Minimalist exception hierarchy generator", "AUTHOR" => "David Golden ", "BUILD_REQUIRES" => {}, "CONFIGURE_REQUIRES" => { "ExtUtils::MakeMaker" => "6.17" }, "DISTNAME" => "failures", "EXE_FILES" => [], "LICENSE" => "apache", "NAME" => "failures", "PREREQ_PM" => { "Carp" => 0, "Class::Tiny" => 0, "overload" => 0, "parent" => 0, "strict" => 0, "warnings" => 0 }, "TEST_REQUIRES" => { "Exporter" => 0, "ExtUtils::MakeMaker" => 0, "File::Spec::Functions" => 0, "List::Util" => 0, "Test::More" => "0.96", "lib" => 0 }, "VERSION" => "0.003", "test" => { "TESTS" => "t/*.t" } ); my %FallbackPrereqs = ( "Carp" => 0, "Class::Tiny" => 0, "Exporter" => 0, "ExtUtils::MakeMaker" => 0, "File::Spec::Functions" => 0, "List::Util" => 0, "Test::More" => "0.96", "lib" => 0, "overload" => 0, "parent" => 0, "strict" => 0, "warnings" => 0 ); unless ( eval { ExtUtils::MakeMaker->VERSION(6.63_03) } ) { delete $WriteMakefileArgs{TEST_REQUIRES}; delete $WriteMakefileArgs{BUILD_REQUIRES}; $WriteMakefileArgs{PREREQ_PM} = \%FallbackPrereqs; } delete $WriteMakefileArgs{CONFIGURE_REQUIRES} unless eval { ExtUtils::MakeMaker->VERSION(6.52) }; WriteMakefile(%WriteMakefileArgs); failures-0.003/MANIFEST000644 000765 000024 00000001034 12263033624 014710 0ustar00davidstaff000000 000000 # This file was automatically generated by Dist::Zilla::Plugin::Manifest v5.008. CONTRIBUTING Changes LICENSE MANIFEST META.json META.yml Makefile.PL README cpanfile dist.ini lib/custom/failures.pm lib/failures.pm perlcritic.rc t/00-report-prereqs.t t/basic.t t/custom.t t/lib/MyFailures.pm t/lib/TestThrower.pm tidyall.ini xt/author/00-compile.t xt/author/critic.t xt/author/pod-spell.t xt/release/distmeta.t xt/release/minimum-version.t xt/release/pod-coverage.t xt/release/pod-syntax.t xt/release/portability.t xt/release/test-version.t failures-0.003/META.json000644 000765 000024 00000005320 12263033624 015202 0ustar00davidstaff000000 000000 { "abstract" : "Minimalist exception hierarchy generator", "author" : [ "David Golden " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 5.008, CPAN::Meta::Converter version 2.132830", "license" : [ "apache_2_0" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "failures", "no_index" : { "directory" : [ "t", "xt", "examples", "corpus" ], "package" : [ "DB" ] }, "prereqs" : { "configure" : { "requires" : { "ExtUtils::MakeMaker" : "6.17" } }, "develop" : { "requires" : { "Dist::Zilla" : "5.008", "Dist::Zilla::Plugin::Prereqs" : "0", "Dist::Zilla::Plugin::RemovePrereqs" : "0", "Dist::Zilla::PluginBundle::DAGOLDEN" : "0.053", "File::Spec" : "0", "File::Temp" : "0", "IO::Handle" : "0", "IPC::Open3" : "0", "Pod::Coverage::TrustPod" : "0", "Test::CPAN::Meta" : "0", "Test::More" : "0", "Test::Pod" : "1.41", "Test::Pod::Coverage" : "1.08" } }, "runtime" : { "requires" : { "Carp" : "0", "Class::Tiny" : "0", "overload" : "0", "parent" : "0", "perl" : "5.008001", "strict" : "0", "warnings" : "0" } }, "test" : { "recommends" : { "CPAN::Meta" : "0", "CPAN::Meta::Requirements" : "0", "Test::FailWarnings" : "0.007" }, "requires" : { "Exporter" : "0", "ExtUtils::MakeMaker" : "0", "File::Spec::Functions" : "0", "List::Util" : "0", "Test::More" : "0.96", "lib" : "0" } } }, "provides" : { "custom::failures" : { "file" : "lib/custom/failures.pm", "version" : "0.003" }, "failure" : { "file" : "lib/failures.pm", "version" : "0.003" }, "failures" : { "file" : "lib/failures.pm", "version" : "0.003" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/dagolden/failures/issues" }, "homepage" : "https://github.com/dagolden/failures", "repository" : { "type" : "git", "url" : "https://github.com/dagolden/failures.git", "web" : "https://github.com/dagolden/failures" } }, "version" : "0.003", "x_authority" : "cpan:DAGOLDEN" } failures-0.003/META.yml000644 000765 000024 00000002116 12263033624 015032 0ustar00davidstaff000000 000000 --- abstract: 'Minimalist exception hierarchy generator' author: - 'David Golden ' build_requires: Exporter: 0 ExtUtils::MakeMaker: 0 File::Spec::Functions: 0 List::Util: 0 Test::More: 0.96 lib: 0 configure_requires: ExtUtils::MakeMaker: 6.17 dynamic_config: 0 generated_by: 'Dist::Zilla version 5.008, CPAN::Meta::Converter version 2.132830' license: apache meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: 1.4 name: failures no_index: directory: - t - xt - examples - corpus package: - DB provides: custom::failures: file: lib/custom/failures.pm version: 0.003 failure: file: lib/failures.pm version: 0.003 failures: file: lib/failures.pm version: 0.003 requires: Carp: 0 Class::Tiny: 0 overload: 0 parent: 0 perl: 5.008001 strict: 0 warnings: 0 resources: bugtracker: https://github.com/dagolden/failures/issues homepage: https://github.com/dagolden/failures repository: https://github.com/dagolden/failures.git version: 0.003 x_authority: cpan:DAGOLDEN failures-0.003/perlcritic.rc000644 000765 000024 00000001166 12263033624 016253 0ustar00davidstaff000000 000000 severity = 5 verbose = 8 [Variables::ProhibitPunctuationVars] allow = $@ $! [TestingAndDebugging::ProhibitNoStrict] allow = refs [Variables::ProhibitEvilVariables] variables = $DB::single # Turn these off [-BuiltinFunctions::ProhibitStringyEval] [-ControlStructures::ProhibitPostfixControls] [-ControlStructures::ProhibitUnlessBlocks] [-Documentation::RequirePodSections] [-InputOutput::ProhibitInteractiveTest] [-References::ProhibitDoubleSigils] [-RegularExpressions::RequireExtendedFormatting] [-InputOutput::ProhibitTwoArgOpen] [-Modules::ProhibitEvilModules] # Turn this on [Lax::ProhibitStringyEval::ExceptForRequire] failures-0.003/README000644 000765 000024 00000015454 12263033624 014452 0ustar00davidstaff000000 000000 NAME failures - Minimalist exception hierarchy generator VERSION version 0.003 SYNOPSIS use failures qw/io::file io::network/; use Try::Tiny; use Safe::Isa; # for $_isa try { process_file or failure::io::file->throw("oops, something bad happened: $!"); } catch { if ( $_->$_isa("failure::io::file") ) { ... } elsif( $_->$_isa("failure::io") ) { ... } elsif( $_->$_isa("failure") ) { ... } else { ... } } DESCRIPTION This module lets you define an exception hierarchy quickly and simply. Here were my design goals: * minimalist interface * 80% of features in 20% of lines of code * depend only on core modules (nearly achieved) * support hierarchical error types * identify errors types by name (class) not by parsing strings * leave (possibly expensive) trace decisions to the thrower Currently, "failures" is implemented in under 70 lines of code. Failure objects are implemented with Class::Tiny to allow easy subclassing (see custom::failures), but "Class::Tiny" only requires core modules, so other than that exception, the 'core only' goal is achieved. USAGE Defining failure categories use failures qw/foo::bar foo::baz/; This will define the following classes in the "failure" namespace: * "failure" * "failure::foo" * "failure::foo::bar" * "failure::foo::baz" Subclasses inherit, so "failure::foo::bar" is-a "failure::foo" and "failure::foo" is-a "failure". Attributes A failure class has three attributes: "msg", "payload", and "trace". Their usage is described below. Accessors exist for all three. Throwing failures The "throw" method of a failure class takes a single, optional argument that modifies how failure objects are stringified. If no argument is given, a default message is generated if the object is stringified: say failure::foo::bar->throw; # Caught failure::foo::bar With a single, non-hash-reference argument, the argument is used for the "msg" attribute and is appended if the object is stringified. say failure::foo::bar->throw("Ouch!"); # Caught failure::foo::bar: Ouch! With a hash reference argument, the "msg" key provides the string to append to the default error. If you have extra data to attach to the exception, use the "payload" key: failure::foo::bar->throw({ msg => "Ouch!", payload => $extra_data, }); If an optional "trace" key is provided, it is appended if the object is stringified. To loosely emulate "die" and provide a simple filename and line number, use the "failure->line_trace" class method: failure::foo::bar->throw({ msg => "Ouch!", trace => failure->line_trace, }); # Caught failure::foo::bar: Ouch! # # Failure caught at line To provide a trace just like the Carp module (including respecting @CARP_NOT) use the "croak_trace" or "confess_trace" class methods: failure::foo::bar->throw({ msg => "Ouch!", trace => failure->croak_trace, }); # Caught failure::foo::bar: Ouch! # # Failure caught at line failure::foo::bar->throw({ msg => "Ouch!", trace => failure->confess_trace, }); # Caught failure::foo::bar: Ouch! # # Failure caught at line # [confess stack trace continues] You can provide a "trace" key with any object that overrides stringification, like Devel::StackTrace: failure::foo::bar->throw({ msg => "Ouch!", trace => Devel::StackTrace->new, }); # Caught failure::foo::bar: Ouch! # # [stringified Devel::StackTrace object] Catching failures Use Try::Tiny, of course. Within a catch block, you know that $_ is defined, but it still might be an unblessed reference or something that is risky to call "isa" on. If you load Safe::Isa, you get a code reference in $_isa that calls "isa" only on objects. So catching looks like this: use Try::Tiny; use Safe::Isa; try { ... } catch { if ( $_->$_isa("failure::foo") ) { # handle it } }; If you need to rethrow the exception, just use "die": elsif ( $_->$_isa("failure") ) { die $_; } Overriding failure class behavior See custom::failures. SEE ALSO There are many error/exception systems on CPAN. This one is designed to be minimalist. If you have more complex or substantial needs, people I know and trust seem to be recommending: * Throwable — exceptions as a Moo/Moose role * Throwable::X — Throwable extended with extra goodies Here are other modules I found that weren't appropriate for my needs or didn't suit my taste: * Class::Throwable — no hierarchy and always builds a full stack trace * Error::Tiny — blends Try::Tiny and a trivial exception base class * Exception::Base — complexity on par with Exception::Class, but highly optimized for speed * Exception::Class — once highly recommended, but even the author now suggests Throwable * Exception::Simple — very simple, but always uses "caller" and has no hierarchy * Exception::Tiny — not bad, but always uses "caller" and setting up a hierarchy requires extra work * Ouch — simple, well-thought out, but no hierarchy; also cutesy function names Here are some that I'm very dubious about: * Err — alpha since 2012 * Error — no longer recommended by maintainer * errors — "still under design" since 2009 * Exception — dates back to 1996 and undocumented SUPPORT Bugs / Feature Requests Please report any bugs or feature requests through the issue tracker at . You will be notified automatically of any progress on your issue. Source Code This is open source software. The code repository is available for public review and contribution under the terms of the license. git clone https://github.com/dagolden/failures.git AUTHOR David Golden COPYRIGHT AND LICENSE This software is Copyright (c) 2013 by David Golden. This is free software, licensed under: The Apache License, Version 2.0, January 2004 failures-0.003/t/000755 000765 000024 00000000000 12263033624 014024 5ustar00davidstaff000000 000000 failures-0.003/tidyall.ini000644 000765 000024 00000000240 12263033624 015720 0ustar00davidstaff000000 000000 ; Install Code::TidyAll ; run "tidyall -a" to tidy all files ; run "tidyall -g" to tidy only files modified from git [PerlTidy] select = {lib,t}/**/*.{pl,pm,t} failures-0.003/xt/000755 000765 000024 00000000000 12263033624 014214 5ustar00davidstaff000000 000000 failures-0.003/xt/author/000755 000765 000024 00000000000 12263033624 015516 5ustar00davidstaff000000 000000 failures-0.003/xt/release/000755 000765 000024 00000000000 12263033624 015634 5ustar00davidstaff000000 000000 failures-0.003/xt/release/distmeta.t000644 000765 000024 00000000332 12263033624 017631 0ustar00davidstaff000000 000000 #!perl # This file was automatically generated by Dist::Zilla::Plugin::MetaTests. use Test::More; eval "use Test::CPAN::Meta"; plan skip_all => "Test::CPAN::Meta required for testing META.yml" if $@; meta_yaml_ok(); failures-0.003/xt/release/minimum-version.t000644 000765 000024 00000000266 12263033624 021163 0ustar00davidstaff000000 000000 #!perl use Test::More; eval "use Test::MinimumVersion"; plan skip_all => "Test::MinimumVersion required for testing minimum versions" if $@; all_minimum_version_ok( qq{5.010} ); failures-0.003/xt/release/pod-coverage.t000644 000765 000024 00000000651 12263033624 020376 0ustar00davidstaff000000 000000 #!perl # This file was automatically generated by Dist::Zilla::Plugin::PodCoverageTests. use Test::More; eval "use Test::Pod::Coverage 1.08"; plan skip_all => "Test::Pod::Coverage 1.08 required for testing POD coverage" if $@; eval "use Pod::Coverage::TrustPod"; plan skip_all => "Pod::Coverage::TrustPod required for testing POD coverage" if $@; all_pod_coverage_ok({ coverage_class => 'Pod::Coverage::TrustPod' }); failures-0.003/xt/release/pod-syntax.t000644 000765 000024 00000000332 12263033624 020125 0ustar00davidstaff000000 000000 #!perl # This file was automatically generated by Dist::Zilla::Plugin::PodSyntaxTests. use Test::More; eval "use Test::Pod 1.41"; plan skip_all => "Test::Pod 1.41 required for testing POD" if $@; all_pod_files_ok(); failures-0.003/xt/release/portability.t000644 000765 000024 00000000332 12263033624 020361 0ustar00davidstaff000000 000000 #!perl use strict; use warnings; use Test::More; eval 'use Test::Portability::Files'; plan skip_all => 'Test::Portability::Files required for testing portability' if $@; options(test_one_dot => 0); run_tests(); failures-0.003/xt/release/test-version.t000644 000765 000024 00000000643 12263033624 020466 0ustar00davidstaff000000 000000 use strict; use warnings; use Test::More; # generated by Dist::Zilla::Plugin::Test::Version 0.002004 BEGIN { eval "use Test::Version; 1;" or die $@; } my @imports = ( 'version_all_ok' ); my $params = { is_strict => 0, has_version => 1, }; push @imports, $params if version->parse( $Test::Version::VERSION ) >= version->parse('1.002'); Test::Version->import(@imports); version_all_ok; done_testing; failures-0.003/xt/author/00-compile.t000644 000765 000024 00000002064 12263033624 017552 0ustar00davidstaff000000 000000 use 5.006; use strict; use warnings; # this test was generated with Dist::Zilla::Plugin::Test::Compile 2.039 use Test::More tests => 2 + ($ENV{AUTHOR_TESTING} ? 1 : 0); my @module_files = ( 'custom/failures.pm', 'failures.pm' ); # fake home for cpan-testers use File::Temp; local $ENV{HOME} = File::Temp::tempdir( CLEANUP => 1 ); my $inc_switch = -d 'blib' ? '-Mblib' : '-Ilib'; use File::Spec; use IPC::Open3; use IO::Handle; open my $stdin, '<', File::Spec->devnull or die "can't open devnull: $!"; my @warnings; for my $lib (@module_files) { # see L my $stderr = IO::Handle->new; my $pid = open3($stdin, '>&STDERR', $stderr, $^X, $inc_switch, '-e', "require q[$lib]"); binmode $stderr, ':crlf' if $^O eq 'MSWin32'; my @_warnings = <$stderr>; waitpid($pid, 0); is($?, 0, "$lib loaded ok"); if (@_warnings) { warn @_warnings; push @warnings, @_warnings; } } is(scalar(@warnings), 0, 'no warnings found') if $ENV{AUTHOR_TESTING}; failures-0.003/xt/author/critic.t000644 000765 000024 00000000435 12263033624 017162 0ustar00davidstaff000000 000000 #!perl use strict; use warnings; use Test::More; use English qw(-no_match_vars); eval "use Test::Perl::Critic"; plan skip_all => 'Test::Perl::Critic required to criticise code' if $@; Test::Perl::Critic->import( -profile => "perlcritic.rc" ) if -e "perlcritic.rc"; all_critic_ok(); failures-0.003/xt/author/pod-spell.t000644 000765 000024 00000000441 12263033624 017601 0ustar00davidstaff000000 000000 use strict; use warnings; use Test::More; # generated by Dist::Zilla::Plugin::Test::PodSpelling 2.006002 use Test::Spelling 0.12; use Pod::Wordlist; add_stopwords(); all_pod_files_spelling_ok( qw( bin lib ) ); __DATA__ rethrow Throwable David Golden dagolden lib custom failures failures-0.003/t/00-report-prereqs.t000644 000765 000024 00000006667 12263033624 017437 0ustar00davidstaff000000 000000 #!perl use strict; use warnings; # This test was generated by Dist::Zilla::Plugin::Test::ReportPrereqs 0.010 use Test::More tests => 1; use ExtUtils::MakeMaker; use File::Spec::Functions; use List::Util qw/max/; my @modules = qw( CPAN::Meta CPAN::Meta::Requirements Carp Class::Tiny Exporter ExtUtils::MakeMaker File::Spec::Functions List::Util Test::FailWarnings Test::More lib overload parent perl strict warnings ); my %exclude = map {; $_ => 1 } qw( ); my ($source) = grep { -f $_ } qw/MYMETA.json MYMETA.yml META.json/; $source = "META.yml" unless defined $source; # replace modules with dynamic results from MYMETA.json if we can # (hide CPAN::Meta from prereq scanner) my $cpan_meta = "CPAN::Meta"; my $cpan_meta_req = "CPAN::Meta::Requirements"; my $all_requires; if ( -f $source && eval "require $cpan_meta" ) { ## no critic if ( my $meta = eval { CPAN::Meta->load_file($source) } ) { # Get ALL modules mentioned in META (any phase/type) my $prereqs = $meta->prereqs; delete $prereqs->{develop} if not $ENV{AUTHOR_TESTING}; my %uniq = map {$_ => 1} map { keys %$_ } map { values %$_ } values %$prereqs; $uniq{$_} = 1 for @modules; # don't lose any static ones @modules = sort grep { ! $exclude{$_} } keys %uniq; # If verifying, merge 'requires' only for major phases if ( 1 ) { $prereqs = $meta->effective_prereqs; # get the object, not the hash if (eval "require $cpan_meta_req; 1") { ## no critic $all_requires = $cpan_meta_req->new; for my $phase ( qw/configure build test runtime/ ) { $all_requires->add_requirements( $prereqs->requirements_for($phase, 'requires') ); } } } } } my @reports = [qw/Version Module/]; my @dep_errors; my $req_hash = defined($all_requires) ? $all_requires->as_string_hash : {}; for my $mod ( @modules ) { next if $mod eq 'perl'; my $file = $mod; $file =~ s{::}{/}g; $file .= ".pm"; my ($prefix) = grep { -e catfile($_, $file) } @INC; if ( $prefix ) { my $ver = MM->parse_version( catfile($prefix, $file) ); $ver = "undef" unless defined $ver; # Newer MM should do this anyway push @reports, [$ver, $mod]; if ( 1 && $all_requires ) { my $req = $req_hash->{$mod}; if ( defined $req && length $req ) { if ( ! defined eval { version->parse($ver) } ) { push @dep_errors, "$mod version '$ver' cannot be parsed (version '$req' required)"; } elsif ( ! $all_requires->accepts_module( $mod => $ver ) ) { push @dep_errors, "$mod version '$ver' is not in required range '$req'"; } } } } else { push @reports, ["missing", $mod]; if ( 1 && $all_requires ) { my $req = $req_hash->{$mod}; if ( defined $req && length $req ) { push @dep_errors, "$mod is not installed (version '$req' required)"; } } } } if ( @reports ) { my $vl = max map { length $_->[0] } @reports; my $ml = max map { length $_->[1] } @reports; splice @reports, 1, 0, ["-" x $vl, "-" x $ml]; diag "\nVersions for all modules listed in $source (including optional ones):\n", map {sprintf(" %*s %*s\n",$vl,$_->[0],-$ml,$_->[1])} @reports; } if ( @dep_errors ) { diag join("\n", "\n*** WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING ***\n", "The following REQUIRED prerequisites were not satisfied:\n", @dep_errors, "\n" ); } pass; # vim: ts=2 sts=2 sw=2 et: failures-0.003/t/basic.t000644 000765 000024 00000006623 12263033624 015301 0ustar00davidstaff000000 000000 use 5.008001; use strict; use warnings; use Test::More 0.96; # use if available eval { require Test::FailWarnings; Test::FailWarnings->import }; use lib 't/lib'; use TestThrower; use failures qw/vogon vogon::jeltz human::arthur/; subtest 'throw unnested failure' => sub { my $err; eval { failure::vogon->throw }; ok( $err = $@, 'caught thrown error' ); isa_ok( $err, $_ ) for qw/failure failure::vogon/; }; subtest 'throw nested failure' => sub { my $err; eval { failure::vogon::jeltz->throw }; ok( $err = $@, 'caught thrown error' ); isa_ok( $err, $_ ) for qw/failure failure::vogon failure::vogon::jeltz/; eval { failure::human::arthur->throw }; ok( $err = $@, 'caught thrown error' ); isa_ok( $err, $_ ) for qw/failure failure::human failure::human::arthur/; }; subtest 'stringification' => sub { my $err; eval { failure::vogon::jeltz->throw }; ok( $err = $@, 'caught thrown error (no message)' ); is( "$err", "Caught failure::vogon::jeltz\n", "stringification (no message)" ); eval { failure::vogon::jeltz->throw("bypass over budget") }; ok( $err = $@, 'caught thrown error (string message)' ); is( "$err", "Caught failure::vogon::jeltz: bypass over budget\n", "stringification (string message)" ); eval { failure::vogon::jeltz->throw( { msg => "bypass over budget" } ) }; ok( $err = $@, 'caught thrown error (message in hashref)' ); is( "$err", "Caught failure::vogon::jeltz: bypass over budget\n", "stringification (message in hashref)" ); }; subtest 'trace' => sub { my $err; eval { failure::vogon::jeltz->throw( { trace => 'STACK TRACE' } ) }; ok( $err = $@, 'caught thrown error (with trace)' ); is( $err->message, "Caught failure::vogon::jeltz", "message method has no trace" ); is( "$err", "Caught failure::vogon::jeltz\n\nSTACK TRACE\n", "stringification has stack trace" ); eval { failure::vogon::jeltz->throw( { trace => failure->line_trace } ) }; ok( $err = $@, 'caught thrown error (with line trace)' ); like( "$err", qr/Caught failure::vogon::jeltz\n\nFailure caught at t\/basic\.t line \d+\.?\n/, "stringification with line trace" ); eval { deep_throw( 'failure::vogon::jeltz', "Ouch!", 'croak_trace' ) }; ok( $err = $@, 'caught thrown error (with croak trace)' ); like( "$err", qr/Caught failure::vogon::jeltz: Ouch!\n\nFailure caught at t\/basic\.t line \d+\.?\n/, "stringification with croak trace" ); eval { deep_throw( 'failure::vogon::jeltz', "Ouch!", 'confess_trace' ) }; ok( $err = $@, 'caught thrown error (with confess trace)' ); like( "$err", qr/Caught failure::vogon::jeltz: Ouch!\n\nFailure caught at t\/lib\/TestThrower\.pm line \d+\.?\n\s+Baz::baz/, "stringification with croak trace" ); }; subtest 'payload' => sub { my $err; my $payload = { foo => 'bar' }; eval { failure::vogon::jeltz->throw( { msg => "bypass over budget", payload => $payload } ); }; ok( $err = $@, 'caught thrown error' ); is_deeply( $err->payload, $payload, "payload is correct" ); }; done_testing; # # This file is part of failures # # This software is Copyright (c) 2013 by David Golden. # # This is free software, licensed under: # # The Apache License, Version 2.0, January 2004 # # vim: ts=4 sts=4 sw=4 et: failures-0.003/t/custom.t000644 000765 000024 00000003762 12263033624 015533 0ustar00davidstaff000000 000000 use 5.008001; use strict; use warnings; use Test::More 0.96; # use if available eval { require Test::FailWarnings; Test::FailWarnings->import }; use lib 't/lib'; use MyFailures; subtest 'custom hierarchy' => sub { no strict 'refs'; for ("MyFailures::io::file") { isa_ok( $_, "MyFailures::io", $_ ) or diag explain \@{"$_\::ISA"}; isa_ok( $_, "failure::io::file", $_ ) or diag explain \@{"$_\::ISA"}; } for ("MyFailures::io") { isa_ok( $_, "MyFailures", $_ ) or diag explain \@{"$_\::ISA"}; isa_ok( $_, "failure::io", $_ ) or diag explain \@{"$_\::ISA"}; } for ("MyFailures") { isa_ok( $_, "failure", $_ ) or diag explain \@{"$_\::ISA"}; } }; subtest 'custom hierarchy in custom namespace' => sub { no strict 'refs'; for ("Other::Failure::io::file") { isa_ok( $_, "Other::Failure::io", $_ ) or diag explain \@{"$_\::ISA"}; isa_ok( $_, "failure::io::file", $_ ) or diag explain \@{"$_\::ISA"}; } for ("Other::Failure::io") { isa_ok( $_, "Other::Failure", $_ ) or diag explain \@{"$_\::ISA"}; isa_ok( $_, "failure::io", $_ ) or diag explain \@{"$_\::ISA"}; } for ("Other::Failure") { isa_ok( $_, "failure", $_ ) or diag explain \@{"$_\::ISA"}; } }; subtest 'custom attributes and methods' => sub { my $err; my $now = time; eval { MyFailures::io::file->throw; }; ok( $err = $@, 'caught thrown error' ); ok( $err->when >= $now, "timestamp attribute populated" ); is( $err->payload, "Hello Payload", "custom throw set payload" ); is( $err->did_build, 1, "BUILD set attribute" ); is( $err->message(''), "Caught MyFailures::io::file: (@{[$err->when]})", "custom message added attribute to string" ); }; done_testing; # # This file is part of failures # # This software is Copyright (c) 2013 by David Golden. # # This is free software, licensed under: # # The Apache License, Version 2.0, January 2004 # # vim: ts=4 sts=4 sw=4 et: failures-0.003/t/lib/000755 000765 000024 00000000000 12263033624 014572 5ustar00davidstaff000000 000000 failures-0.003/t/lib/MyFailures.pm000644 000765 000024 00000001116 12263033624 017207 0ustar00davidstaff000000 000000 use 5.008001; use strict; use warnings; package MyFailures; use custom::failures qw/io::file/; use Class::Tiny { did_build => 0, when => sub { time }, }; sub message { my ( $self, $msg ) = @_; my $when = sprintf( "(%s)", $self->when ); return $self->SUPER::message( length($msg) ? "$when $msg" : $when ); } sub throw { my ( $self, $msg ) = @_; $self->SUPER::throw( { msg => $msg, payload => "Hello Payload" } ); } sub BUILD { my ($self) = @_; $self->did_build(1); } package main; use custom::failures 'Other::Failure' => [qw/io::file/]; 1; failures-0.003/t/lib/TestThrower.pm000644 000765 000024 00000000735 12263033624 017427 0ustar00davidstaff000000 000000 use 5.008001; use strict; use warnings; package TestThrower; use Exporter; our @ISA = qw/Exporter/; our @EXPORT = qw( deep_throw ); our @CARP_NOT = qw/Foo/; sub deep_throw { Foo::foo(@_) } package Foo; our @CARP_NOT = qw/Bar/; sub foo { Bar::bar(@_) } package Bar; our @CARP_NOT = qw/Baz/; sub bar { Baz::baz(@_) } package Baz; sub baz { my ( $class, $msg, $trace_method ) = @_; $class->throw( { msg => $msg, trace => failure->$trace_method } ); } 1; failures-0.003/lib/custom/000755 000765 000024 00000000000 12263033624 015641 5ustar00davidstaff000000 000000 failures-0.003/lib/failures.pm000644 000765 000024 00000021501 12263033624 016476 0ustar00davidstaff000000 000000 use 5.008001; use strict; use warnings; package failures; # ABSTRACT: Minimalist exception hierarchy generator our $VERSION = '0.003'; # VERSION sub import { no strict 'refs'; my ( $class, @failures ) = @_; my $caller = caller; my $is_custom = $class eq 'custom::failures'; if ( $is_custom && ref $failures[1] eq 'ARRAY' ) { $caller = shift @failures; @failures = @{ $failures[0] }; } for my $f (@failures) { # XXX should check $f for valid package name my $custom = $caller; my $default = 'failure'; push @{"$custom\::ISA"}, $default if $is_custom; for my $p ( split /::/, $f ) { push @{"$default\::$p\::ISA"}, $default; $default .= "::$p"; if ($is_custom) { push @{"$custom\::$p\::ISA"}, $custom, $default; $custom .= "::$p"; } } } } package failure; use Class::Tiny { msg => '', trace => '', payload => undef }; use overload ( q{""} => \&as_string, fallback => 1 ); sub throw { my ( $class, $msg ) = @_; my $m = ref $msg eq 'HASH' ? $msg : { msg => $msg }; die $class->new( map { defined $m->{$_} ? ( $_ => $m->{$_} ) : () } keys %$m ); } sub message { my ( $self, $msg ) = @_; my $intro = "Caught @{[ref $self]}"; return defined($msg) && length($msg) ? "$intro: $msg" : $intro; } sub as_string { my ($self) = @_; my ( $message, $trace ) = ( $self->message( $self->msg ), $self->trace ); return length($trace) ? "$message\n\n$trace\n" : "$message\n"; } sub line_trace { my ( undef, $filename, $line ) = caller(0); return "Failure caught at $filename line $line."; } for my $fn (qw/croak_trace confess_trace/) { no strict 'refs'; no warnings 'once'; *{$fn} = sub { require Carp; local @failure::CARP_NOT = ( scalar caller ); chomp( my $trace = $fn eq 'croak_trace' ? Carp::shortmess('') : Carp::longmess('') ); return "Failure caught$trace"; }; } 1; # vim: ts=4 sts=4 sw=4 et: __END__ =pod =encoding UTF-8 =head1 NAME failures - Minimalist exception hierarchy generator =head1 VERSION version 0.003 =head1 SYNOPSIS use failures qw/io::file io::network/; use Try::Tiny; use Safe::Isa; # for $_isa try { process_file or failure::io::file->throw("oops, something bad happened: $!"); } catch { if ( $_->$_isa("failure::io::file") ) { ... } elsif( $_->$_isa("failure::io") ) { ... } elsif( $_->$_isa("failure") ) { ... } else { ... } } =head1 DESCRIPTION This module lets you define an exception hierarchy quickly and simply. Here were my design goals: =over 4 =item * minimalist interface =item * 80% of features in 20% of lines of code =item * depend only on core modules (nearly achieved) =item * support hierarchical error types =item * identify errors types by name (class) not by parsing strings =item * leave (possibly expensive) trace decisions to the thrower =back Currently, C is implemented in under 70 lines of code. Failure objects are implemented with L to allow easy subclassing (see L), but C only requires core modules, so other than that exception, the 'core only' goal is achieved. =head1 USAGE =head2 Defining failure categories use failures qw/foo::bar foo::baz/; This will define the following classes in the C namespace: =over 4 =item * C =item * C =item * C =item * C =back Subclasses inherit, so C is-a C and C is-a C. =head2 Attributes A failure class has three attributes: C, C, and C. Their usage is described below. Accessors exist for all three. =head2 Throwing failures The C method of a failure class takes a single, optional argument that modifies how failure objects are stringified. If no argument is given, a default message is generated if the object is stringified: say failure::foo::bar->throw; # Caught failure::foo::bar With a single, non-hash-reference argument, the argument is used for the C attribute and is appended if the object is stringified. say failure::foo::bar->throw("Ouch!"); # Caught failure::foo::bar: Ouch! With a hash reference argument, the C key provides the string to append to the default error. If you have extra data to attach to the exception, use the C key: failure::foo::bar->throw({ msg => "Ouch!", payload => $extra_data, }); If an optional C key is provided, it is appended if the object is stringified. To loosely emulate C and provide a simple filename and line number, use the C<< failure->line_trace >> class method: failure::foo::bar->throw({ msg => "Ouch!", trace => failure->line_trace, }); # Caught failure::foo::bar: Ouch! # # Failure caught at line To provide a trace just like the L module (including respecting C<@CARP_NOT>) use the C or C class methods: failure::foo::bar->throw({ msg => "Ouch!", trace => failure->croak_trace, }); # Caught failure::foo::bar: Ouch! # # Failure caught at line failure::foo::bar->throw({ msg => "Ouch!", trace => failure->confess_trace, }); # Caught failure::foo::bar: Ouch! # # Failure caught at line # [confess stack trace continues] You can provide a C key with any object that overrides stringification, like L: failure::foo::bar->throw({ msg => "Ouch!", trace => Devel::StackTrace->new, }); # Caught failure::foo::bar: Ouch! # # [stringified Devel::StackTrace object] =head2 Catching failures Use L, of course. Within a catch block, you know that C<$_> is defined, but it still might be an unblessed reference or something that is risky to call C on. If you load L, you get a code reference in C<$_isa> that calls C only on objects. So catching looks like this: use Try::Tiny; use Safe::Isa; try { ... } catch { if ( $_->$_isa("failure::foo") ) { # handle it } }; If you need to rethrow the exception, just use C: elsif ( $_->$_isa("failure") ) { die $_; } =head2 Overriding failure class behavior See L. =for Pod::Coverage throw message as_string =head1 SEE ALSO There are many error/exception systems on CPAN. This one is designed to be minimalist. If you have more complex or substantial needs, people I know and trust seem to be recommending: =over 4 =item * L — exceptions as a Moo/Moose role =item * L — Throwable extended with extra goodies =back Here are other modules I found that weren't appropriate for my needs or didn't suit my taste: =over 4 =item * L — no hierarchy and always builds a full stack trace =item * L — blends Try::Tiny and a trivial exception base class =item * L — complexity on par with Exception::Class, but highly optimized for speed =item * L — once highly recommended, but even the author now suggests Throwable =item * L — very simple, but always uses C and has no hierarchy =item * L — not bad, but always uses C and setting up a hierarchy requires extra work =item * L — simple, well-thought out, but no hierarchy; also cutesy function names =back Here are some that I'm very dubious about: =over 4 =item * L — alpha since 2012 =item * L — no longer recommended by maintainer =item * L — "still under design" since 2009 =item * L — dates back to 1996 and undocumented =back =for :stopwords cpan testmatrix url annocpan anno bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan =head1 SUPPORT =head2 Bugs / Feature Requests Please report any bugs or feature requests through the issue tracker at L. You will be notified automatically of any progress on your issue. =head2 Source Code This is open source software. The code repository is available for public review and contribution under the terms of the license. L git clone https://github.com/dagolden/failures.git =head1 AUTHOR David Golden =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2013 by David Golden. This is free software, licensed under: The Apache License, Version 2.0, January 2004 =cut failures-0.003/lib/custom/failures.pm000644 000765 000024 00000013032 12263033624 020010 0ustar00davidstaff000000 000000 use 5.008001; use strict; use warnings; package custom::failures; # ABSTRACT: Minimalist, customized exception hierarchy generator our $VERSION = '0.003'; # VERSION use parent 'failures'; 1; # vim: ts=4 sts=4 sw=4 et: __END__ =pod =encoding UTF-8 =head1 NAME custom::failures - Minimalist, customized exception hierarchy generator =head1 VERSION version 0.003 =head1 SYNOPSIS package MyApp::failure; use custom::failures qw/io::file io::network/; # customize failure methods… =head1 DESCRIPTION This module works like L but lets you define a customized exception hierarchy if you need a custom namespace, additional attributes, or customized object behaviors. Because failure classes have an C<@ISA> chain and Perl by default uses depth-first-search to resolve method calls, you can override behavior anywhere in the custom hierarchy and it will take precedence over default C behaviors. There are two methods that might be useful to override: =over 4 =item * message =item * throw =back Both are described further, below. =head1 USAGE =head2 Defining a custom failure hierarchy package MyApp::failure; use custom::failures qw/foo::bar/; This will define a failure class hierarchy under the calling package's namespace. The following diagram show the classes that will be created (arrows denote 'is-a' relationships): MyApp::failure::foo::bar --> failure::foo::bar | | V V MyApp::failure::foo --> failure::foo | | V V MyApp::failure --> failure Alternatively, if you want a different namespace for the hierarchy, do it this way: use custom::failures 'MyApp::Error' => [ 'io::file' ]; That will create the following classes and relationships: MyApp::Error::foo::bar --> failure::foo::bar | | V V MyApp::Error::foo --> failure::foo | | V V MyApp::Error --> failure By having custom classes also inherit from a standard namespace, you can throw a custom error class that will still be caught in the standard namespace: try { MyApp::failure::foo::bar->throw; } catch { if ( $_->$_isa( "failure::foo" ) ) { # handle it here } }; =head2 Adding custom attributes Failure classes are implemented with L, so adding attributes is trivially easy: package MyApp::failure; use custom::failures qw/foo::bar/; use Class::Tiny qw/user/; This adds a C attribute to C and all its subclasses so it can be set in the argument to C: MyApp::failure::foo->throw( { msg => "Ouch!", user => "me" } ); Be sure to load C B you load C so that your C<@ISA> is already set up. =head2 Overriding the C method Overriding C lets you modify how the error string is produced. The C method takes a string (typically just the C field) and returns a string. It should not produce or append stack trace information. That is done during object stringification. Call C if you want the standard error text prepended (C<"Caught $class: ...">). For example, if you want to use L to render messages: package MyApp::failure; use custom::failures qw/foo::bar/; use String::Flogger qw/flog/; sub message { my ( $self, $msg ) = @_; return $self->SUPER::message( flog($msg) ); } Then you can pass strings or array references or code references as the C for C: MyApp::failure->throw( "just a string" ); MyApp::failure->throw( [ "show some data %s", $ref ] ); MyApp::failure->throw( sub { call_expensive_sub() } ); Because the C method is only called during stringification (unless you call it yourself), the failure class type can be checked before any expensive rendering is done. =head2 Overriding the C method Overriding C lets you modify the arguments you can provide or ensure that a trace is included. It can take whatever arguments you want and should call C with a hash reference to actually throw the error. For example, to capture the filename associated with file errors: package MyApp::failure; use custom::failures qw/file/; use Class::Tiny qw/filename/; sub throw { my ( $class, $msg, $file ) = @_; my $args = { msg => $msg, filename => $file, trace => failures->croak_trace, }; $self->SUPER::throw( $args ); } sub message { # do something with 'msg' and 'filename' } Later you could use it like this: MyApp::failure::file->throw( opening => $some_file ); =head2 Using BUILD C supports C, so you can also use that to do things with failure objects when thrown. This example logs exceptions as they are built: use Log::Any qw/$log/; sub BUILD { my ($self) = @_; $log->error( $self->message ); } By using C instead of stringifying C<$self>, we log the message but not the trace (if any). =for Pod::Coverage throw message as_string =head1 AUTHOR David Golden =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2013 by David Golden. This is free software, licensed under: The Apache License, Version 2.0, January 2004 =cut