SlideShare ist ein Scribd-Unternehmen logo
1 von 69
Live Fast,
         Die Young,
Leave A Good Looking Corpse
Code Fast,
       die() Early,
Throw Structured Exceptions
Throw Structured Exceptions
    John SJ Anderson / @genehack / dc.pm
        YAPC::NA 2012 ~ Madison WI
“Classic” Perl exceptions
“Classic” Perl exceptions
•   Throw an exception with die()
“Classic” Perl exceptions
•   Throw an exception with die()

•   Or Carp::croak(), Carp::confess(), etc.
“Classic” Perl exceptions
•   Throw an exception with die()

•   Or Carp::croak(), Carp::confess(), etc.

•   TIMTOWTDI!
“Classic” Perl exceptions
•   Throw an exception with die()

•   Or Carp::croak(), Carp::confess(), etc.

•   TIMTOWTDI!

•   Catch an exception with eval {}
“Classic” Perl exceptions
•   Throw an exception with die()

•   Or Carp::croak(), Carp::confess(), etc.

•   TIMTOWTDI!

•   Catch an exception with eval {}

•   Handle an exception by looking at $@
“Classic” Perl exception throwing

 1   #! /usr/bin/perl
 2
 3   use strict;
 4   use warnings;
 5
 6   eval { my $result = this_might_fail() };
 7
 8   if( $@ ) {
 9     # handle the error here
10   }
Problems with “classic” Perl exceptions
Problems with “classic” Perl exceptions


•   $@ can get clobbered
Problems with “classic” Perl exceptions


• $@ can get clobbered

• $@ can get clobbered by code you don’t own
Problems with “classic” Perl exceptions


• $@ can get clobbered

• $@ can get clobbered by code you don’t own

• $@ might be a false value
Problems with “classic” Perl exceptions


• $@ can get clobbered

• $@ can get clobbered by code you don’t own

• $@ might be a false value

• If $@ is a string, you’re depending on duplicated
  information, which will break.
Use Try::Tiny for
“semi-modern” Perl exceptions
Use Try::Tiny for
  “semi-modern” Perl exceptions
• Provides try{}/catch{}/finally{} blocks
Use Try::Tiny for
  “semi-modern” Perl exceptions
• Provides try{}/catch{}/finally{} blocks
• Handles details of properly dealing with complexities
  around $@
Use Try::Tiny for
  “semi-modern” Perl exceptions
• Provides try{}/catch{}/finally{} blocks
• Handles details of properly dealing with complexities
  around $@
• Lightweight and generally Just Works(tm).
Use Try::Tiny for
  “semi-modern” Perl exceptions
• Provides try{}/catch{}/finally{} blocks
• Handles details of properly dealing with complexities
  around $@
• Lightweight and generally Just Works(tm).
• N.b.: you have to end try{}/catch{} with a
  semicolon. Don’t forget this!
Use Try::Tiny for
      “semi-modern” Perl exceptions
 1   #! /usr/bin/perl
 2
 3   use strict;
 4   use warnings;
 5
 6   use Try::Tiny;
 7
 8   try {
 9     my $result = this_might_fail();
10   }
11   catch {
12     # handle the error here
13   };
Problems with
  “semi-modern” Perl exceptions
• $@ can get clobbered
• $@ can get clobbered by code you don’t own
• $@ might be a false value
• If $@ is a string, you’re depending on duplicated
  information, which will break.
Problems with
  “semi-modern” Perl exceptions



• If $@ is a string, you’re depending on duplicated
  information, which will break.
Wait, where’s the duplicated information?
 1   my $answer;
 2   try {
 3      # any of these might throw an exception
 4      my $this = this_might_fail();
 5      my $that = something_else_might_fail();
 6      $answer = combine_them( $this , $that );
 7   }
 8   catch {
 9      # our error is in $_
10      if( $_ =~ /some error/ ) {
11        # handle some error
12      }
13      elsif( $_ =~ /another error/ ) {
14        # handle another error
15      }
16      else { # not sure what the problem is, just give up
17        confess( $_ );
18      }
19   };
Wait, where’s the duplicated information?
 1   my $answer;
 2   try {
 3      # any of these might throw an exception
 4      my $this = this_might_fail();
 5      my $that = something_else_might_fail();
 6      $answer = combine_them( $this , $that );
 7   }
 8   catch {
 9      # our error is in $_
10      if( $_ =~ /some error/ ) {
11        # handle some error
12      }
13      elsif( $_ =~ /another error/ ) {
14        # handle another error
15      }
16      else { # not sure what the problem is, just give up
17        confess( $_ );
18      }
19   };
Wait, where’s the duplicated information?

•   As soon as somebody “fixes” the string in some die()
    somewhere, you’ve potentially broken exception
    handling
Wait, where’s the duplicated information?

•   As soon as somebody “fixes” the string in some die()
    somewhere, you’ve potentially broken exception
    handling
• And you can’t even easily tell where, because it’s
    probably in a regexp that doesn’t look at all like the
    changed string
Wait, where’s the duplicated information?

•   As soon as somebody “fixes” the string in some die()
    somewhere, you’ve potentially broken exception
    handling
• And you can’t even easily tell where, because it’s
    probably in a regexp that doesn’t look at all like the
    changed string
• Even if you have tests for the code in question, do you
    really have test coverage on all your exception cases?
So what’s the solution?
So what’s the solution?

•   die() can also take a reference as an argument
So what’s the solution?

•   die() can also take a reference as an argument

•   So you can die() with an object!
So what’s the solution?

•   die() can also take a reference as an argument

•   So you can die() with an object!

•   Which means you can cram all sorts of useful information into your
    exceptions
So what’s the solution?

•   die() can also take a reference as an argument

•   So you can die() with an object!

•   Which means you can cram all sorts of useful information into your
    exceptions

•   And more importantly, handle them in a structured fashion that’s much less
    brittle than string comparisons
A framework for structured exceptions:
         Exception::Class
use Exception::Class (
    'MyException',
 
    'AnotherException' => { isa => 'MyException' },
 
    'YetAnotherException' => {
        isa         => 'AnotherException',
        description => 'These exceptions are related to IPC'
    },
 
    'ExceptionWithFields' => {
        isa    => 'YetAnotherException',
        fields => [ 'grandiosity', 'quixotic' ],
    },
);
A framework for structured exceptions:
        Exception::Class
# try
eval { MyException->throw( error => 'I feel funny.' ) };
 
my $e; 
# catch
if ( $e = Exception::Class->caught('MyException') ) {
    warn $e->error, "n", $e->trace->as_string, "n";
    warn join ' ', $e->euid, $e->egid, $e->uid, $e->gid, $e->pid;
    exit;
}
elsif ( $e = Exception::Class->caught('ExceptionWithFields') ) {
    $e->quixotic ? do_something_wacky() : do_something_sane();
}
else {
    $e = Exception::Class->caught();
    ref $e ? $e->rethrow : die $e;
}
Exception::Class Pros
Exception::Class Pros

• Nice declarative syntax
Exception::Class Pros

• Nice declarative syntax
• Possible to declare detailed or simple exception class
  hierarchies very simply
Exception::Class Pros

• Nice declarative syntax
• Possible to declare detailed or simple exception class
    hierarchies very simply
•   Supports aliasing to make throwing particular exception
    types easier
Exception::Class Cons
Exception::Class Cons

•   Not really designed for use with Try::Tiny
Exception::Class Cons

•   Not really designed for use with Try::Tiny

•   Based on Class::Data::Inheritable, not Moose
A Moose role for structured exceptions:
             Throwable
package Redirect;
use Moose;
with 'Throwable';
 
has url => (is => 'ro');


...then later...



Redirect->throw({ url => $url });
Throwable Pros
Throwable Pros
•   Implemented as a Moose role, so your exception
    classes are just normal Moose classes that consume
    the role
Throwable Pros
•   Implemented as a Moose role, so your exception
    classes are just normal Moose classes that consume
    the role

• So you get the usual Moose-y good stuff around
    attributes and methods and such.
Throwable Pros
•   Implemented as a Moose role, so your exception
    classes are just normal Moose classes that consume
    the role

• So you get the usual Moose-y good stuff around
    attributes and methods and such.
• Comes with a grab-bag of typical exception behaviors
    (in Throwable::X), like stack traces, printf-ish
    messages, etc.
Throwable Cons
Throwable Cons


      ?
Throwable Cons


               ?
 So far, I haven’t really found any.
Throwable Cons


                      ?
        So far, I haven’t really found any.
(Of course, that doesn’t mean there aren’t any...)
Error Handling
          Patterns & Anti-Patterns
• DO use exceptions instead of error flags
• DO throw exceptions as early as possible
• DON’T catch exceptions unless you’re going to handle
  them – just let them propagate upwards
• DO design your web application-level error actions to
  handle your business logic-level exceptions
Use exceptions instead of error flags

 1 sub some_catalyst_action :Local {
 2   my( $self , $c ) = @_;
 3   my $session = get_huge_session_object( $c->session );
 4
 5   my $validated_params = validate_request_params( $c->request->params )
 6     or $c->detach( 'error' );
 7
 8   my $step_one_result = $c->model('BusinessLogic')->do_step_one( $session , $validated_params );
 9   $c->detach( 'error' ) if $session->has_error();
10
11   my $step_two_result = $c->model('BusinessLogic')->do_step_two( $step_one_result, $session );
12   $c->detach( 'error' ) if $session->has_error();
13 }
Use exceptions instead of error flags




   Please please please don’t write code like this!
Use exceptions instead of error flags
Use exceptions instead of error flags
•   Forget just one of those checks and you’ve got a hard to track
    down bug
Use exceptions instead of error flags
•   Forget just one of those checks and you’ve got a hard to track
    down bug

•   $session is being passed just to provide access to that error
    flag.
Use exceptions instead of error flags
•   Forget just one of those checks and you’ve got a hard to track
    down bug

•   $session is being passed just to provide access to that error
    flag.

•   The error action gets no real info about what the problem was,
    or it tries to pull it from $session itself (which has its own
    problems)
Use exceptions instead of error flags
 1 sub some_catalyst_action :Local {
 2   my( $self , $c ) = @_;
 3
 4   try {
 5     my $validated_params = validate_request_params( $c->request->params )
 6
 7     my $step_one_result = $c->model('BusinessLogic')->do_step_one( $session , $validated_params );
 8
 9     my $step_two_result = $c->model('BusinessLogic')->do_step_two( $step_one_result, $session );
10   }
11   catch { $c->detach( 'error' , [ $_ ] ) };
12 }
Throw exceptions as early as
         possible
Throw exceptions as early as
         possible
• If you’re going to throw an exception because you
  didn’t get passed something, do it ASAP.
Throw exceptions as early as
         possible
• If you’re going to throw an exception because you
  didn’t get passed something, do it ASAP.

• In general, the quicker you can die(), the better –
  because it reduces the amount of code that might
  contain the bug.
Don’t catch exceptions
except to handle them
Don’t catch exceptions
     except to handle them
• Most of the time, your business logic code is going to
  throw exceptions, not catch them
Don’t catch exceptions
     except to handle them
• Most of the time, your business logic code is going to
  throw exceptions, not catch them
• If you do catch an exception, you should be trying to fix
  the problem.
Don’t catch exceptions
      except to handle them
• Most of the time, your business logic code is going to
    throw exceptions, not catch them
• If you do catch an exception, you should be trying to fix
    the problem.
•   Don’t catch exceptions just to munge them or log them
    and re-throw them. Munge them or log them before
    you throw them.
Further reading
•   Throwable::X: common behavior for thrown exceptions
    (<http://rjbs.manxome.org/rubric/entry/1860>)

•   Exceptionally Extensible Exceptions
    (<http://advent.rjbs.manxome.org/2010/2010-12-03.html>)


•   Structured Data and Knowing versus Guessing

    (<http://www.modernperlbooks.com/mt/2010/10/structured-data-and-knowing-versus-guessing.html>)
Thanks!
Questions?
Further reading
•   Throwable::X: common behavior for thrown exceptions
    (<http://rjbs.manxome.org/rubric/entry/1860>)

•   Exceptionally Extensible Exceptions
    (<http://advent.rjbs.manxome.org/2010/2010-12-03.html>)


•   Structured Data and Knowing versus Guessing

    (<http://www.modernperlbooks.com/mt/2010/10/structured-data-and-knowing-versus-guessing.html>)

Weitere ähnliche Inhalte

Was ist angesagt?

Drupal 8: A story of growing up and getting off the island
Drupal 8: A story of growing up and getting off the islandDrupal 8: A story of growing up and getting off the island
Drupal 8: A story of growing up and getting off the islandAngela Byron
 
Introduction To Moose
Introduction To MooseIntroduction To Moose
Introduction To MooseMike Whitaker
 
Real world gobbledygook
Real world gobbledygookReal world gobbledygook
Real world gobbledygookPawel Szulc
 
Monads asking the right question
Monads  asking the right questionMonads  asking the right question
Monads asking the right questionPawel Szulc
 
Python WATs: Uncovering Odd Behavior
Python WATs: Uncovering Odd BehaviorPython WATs: Uncovering Odd Behavior
Python WATs: Uncovering Odd BehaviorAmy Hanlon
 
A comparison between C# and Java
A comparison between C# and JavaA comparison between C# and Java
A comparison between C# and JavaAli MasudianPour
 
Taking the boilerplate out of your tests with Sourcery
Taking the boilerplate out of your tests with SourceryTaking the boilerplate out of your tests with Sourcery
Taking the boilerplate out of your tests with SourceryVincent Pradeilles
 
Bioinformatics p5-bioperl v2013-wim_vancriekinge
Bioinformatics p5-bioperl v2013-wim_vancriekingeBioinformatics p5-bioperl v2013-wim_vancriekinge
Bioinformatics p5-bioperl v2013-wim_vancriekingeProf. Wim Van Criekinge
 
Clean code with google guava jee conf
Clean code with google guava jee confClean code with google guava jee conf
Clean code with google guava jee confIgor Anishchenko
 
Dan Shappir "JavaScript Riddles For Fun And Profit"
Dan Shappir "JavaScript Riddles For Fun And Profit"Dan Shappir "JavaScript Riddles For Fun And Profit"
Dan Shappir "JavaScript Riddles For Fun And Profit"Fwdays
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)RORLAB
 
Strong typing @ php leeds
Strong typing  @ php leedsStrong typing  @ php leeds
Strong typing @ php leedsDamien Seguy
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidJordi Gerona
 
Everything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insEverything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insAndrew Dupont
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan Stefanov
 
Selfish presentation - ruby internals
Selfish presentation - ruby internalsSelfish presentation - ruby internals
Selfish presentation - ruby internalsWojciech Widenka
 

Was ist angesagt? (20)

JavaScript Primer
JavaScript PrimerJavaScript Primer
JavaScript Primer
 
Drupal 8: A story of growing up and getting off the island
Drupal 8: A story of growing up and getting off the islandDrupal 8: A story of growing up and getting off the island
Drupal 8: A story of growing up and getting off the island
 
Introduction To Moose
Introduction To MooseIntroduction To Moose
Introduction To Moose
 
Real world gobbledygook
Real world gobbledygookReal world gobbledygook
Real world gobbledygook
 
Monads asking the right question
Monads  asking the right questionMonads  asking the right question
Monads asking the right question
 
Python WATs: Uncovering Odd Behavior
Python WATs: Uncovering Odd BehaviorPython WATs: Uncovering Odd Behavior
Python WATs: Uncovering Odd Behavior
 
A comparison between C# and Java
A comparison between C# and JavaA comparison between C# and Java
A comparison between C# and Java
 
Taking the boilerplate out of your tests with Sourcery
Taking the boilerplate out of your tests with SourceryTaking the boilerplate out of your tests with Sourcery
Taking the boilerplate out of your tests with Sourcery
 
Bioinformatics p5-bioperl v2013-wim_vancriekinge
Bioinformatics p5-bioperl v2013-wim_vancriekingeBioinformatics p5-bioperl v2013-wim_vancriekinge
Bioinformatics p5-bioperl v2013-wim_vancriekinge
 
Clean code with google guava jee conf
Clean code with google guava jee confClean code with google guava jee conf
Clean code with google guava jee conf
 
Bioinformatica p6-bioperl
Bioinformatica p6-bioperlBioinformatica p6-bioperl
Bioinformatica p6-bioperl
 
Attribute
AttributeAttribute
Attribute
 
Dan Shappir "JavaScript Riddles For Fun And Profit"
Dan Shappir "JavaScript Riddles For Fun And Profit"Dan Shappir "JavaScript Riddles For Fun And Profit"
Dan Shappir "JavaScript Riddles For Fun And Profit"
 
Floggy-M3DD-2009-01-21
Floggy-M3DD-2009-01-21Floggy-M3DD-2009-01-21
Floggy-M3DD-2009-01-21
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)
 
Strong typing @ php leeds
Strong typing  @ php leedsStrong typing  @ php leeds
Strong typing @ php leeds
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & Android
 
Everything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insEverything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-ins
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Selfish presentation - ruby internals
Selfish presentation - ruby internalsSelfish presentation - ruby internals
Selfish presentation - ruby internals
 

Ähnlich wie Code Fast, Die Young, Throw Structured Exceptions

Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation TutorialLorna Mitchell
 
Code with Style - PyOhio
Code with Style - PyOhioCode with Style - PyOhio
Code with Style - PyOhioClayton Parker
 
Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Benjamin Bock
 
A Scala Corrections Library
A Scala Corrections LibraryA Scala Corrections Library
A Scala Corrections LibraryPaul Phillips
 
Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyWen-Tien Chang
 
Php Crash Course - Macq Electronique 2010
Php Crash Course - Macq Electronique 2010Php Crash Course - Macq Electronique 2010
Php Crash Course - Macq Electronique 2010Michelangelo van Dam
 
The things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaThe things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaKonrad Malawski
 
Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Damien Seguy
 
An OCaml newbie meets Camlp4 parser
An OCaml newbie meets Camlp4 parserAn OCaml newbie meets Camlp4 parser
An OCaml newbie meets Camlp4 parserKiwamu Okabe
 
Slot Composition
Slot CompositionSlot Composition
Slot CompositionESUG
 
Scripting3
Scripting3Scripting3
Scripting3Nao Dara
 
Dev traning 2016 basics of PHP
Dev traning 2016   basics of PHPDev traning 2016   basics of PHP
Dev traning 2016 basics of PHPSacheen Dhanjie
 
Proposed PHP function: is_literal()
Proposed PHP function: is_literal()Proposed PHP function: is_literal()
Proposed PHP function: is_literal()Craig Francis
 
Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practicesSultan Khan
 
Regular Expressions: Backtracking, and The Little Engine that Could(n't)?
Regular Expressions: Backtracking, and The Little Engine that Could(n't)?Regular Expressions: Backtracking, and The Little Engine that Could(n't)?
Regular Expressions: Backtracking, and The Little Engine that Could(n't)?daoswald
 
New land of error handling in swift
New land of error handling in swiftNew land of error handling in swift
New land of error handling in swiftTsungyu Yu
 

Ähnlich wie Code Fast, Die Young, Throw Structured Exceptions (20)

Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
Code with style
Code with styleCode with style
Code with style
 
Code with Style - PyOhio
Code with Style - PyOhioCode with Style - PyOhio
Code with Style - PyOhio
 
Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)
 
A Scala Corrections Library
A Scala Corrections LibraryA Scala Corrections Library
A Scala Corrections Library
 
Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in Ruby
 
Modern Perl
Modern PerlModern Perl
Modern Perl
 
Php Crash Course - Macq Electronique 2010
Php Crash Course - Macq Electronique 2010Php Crash Course - Macq Electronique 2010
Php Crash Course - Macq Electronique 2010
 
The things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaThe things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and Akka
 
Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)
 
An OCaml newbie meets Camlp4 parser
An OCaml newbie meets Camlp4 parserAn OCaml newbie meets Camlp4 parser
An OCaml newbie meets Camlp4 parser
 
Php 2
Php 2Php 2
Php 2
 
Slot Composition
Slot CompositionSlot Composition
Slot Composition
 
Slot Composition
Slot CompositionSlot Composition
Slot Composition
 
Scripting3
Scripting3Scripting3
Scripting3
 
Dev traning 2016 basics of PHP
Dev traning 2016   basics of PHPDev traning 2016   basics of PHP
Dev traning 2016 basics of PHP
 
Proposed PHP function: is_literal()
Proposed PHP function: is_literal()Proposed PHP function: is_literal()
Proposed PHP function: is_literal()
 
Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practices
 
Regular Expressions: Backtracking, and The Little Engine that Could(n't)?
Regular Expressions: Backtracking, and The Little Engine that Could(n't)?Regular Expressions: Backtracking, and The Little Engine that Could(n't)?
Regular Expressions: Backtracking, and The Little Engine that Could(n't)?
 
New land of error handling in swift
New land of error handling in swiftNew land of error handling in swift
New land of error handling in swift
 

Mehr von John Anderson

Introduction to Git (even for non-developers)
Introduction to Git (even for non-developers)Introduction to Git (even for non-developers)
Introduction to Git (even for non-developers)John Anderson
 
Logs are-magic-devfestweekend2018
Logs are-magic-devfestweekend2018Logs are-magic-devfestweekend2018
Logs are-magic-devfestweekend2018John Anderson
 
Logs Are Magic: Why Git Workflows and Commit Structure Should Matter To You
Logs Are Magic: Why Git Workflows and Commit Structure Should Matter To YouLogs Are Magic: Why Git Workflows and Commit Structure Should Matter To You
Logs Are Magic: Why Git Workflows and Commit Structure Should Matter To YouJohn Anderson
 
A static site generator should be your next language learning project
A static site generator should be your next language learning projectA static site generator should be your next language learning project
A static site generator should be your next language learning projectJohn Anderson
 
Do you want to be right or do you want to WIN?
Do you want to be right or do you want to WIN?Do you want to be right or do you want to WIN?
Do you want to be right or do you want to WIN?John Anderson
 
An Introduction to Git (even for non-developers)
An Introduction to Git (even for non-developers)An Introduction to Git (even for non-developers)
An Introduction to Git (even for non-developers)John Anderson
 
You got chocolate in my peanut butter! .NET on Mac & Linux
You got chocolate in my peanut butter! .NET on Mac & LinuxYou got chocolate in my peanut butter! .NET on Mac & Linux
You got chocolate in my peanut butter! .NET on Mac & LinuxJohn Anderson
 
A static site generator should be your next language learning project
A static site generator should be your next language learning projectA static site generator should be your next language learning project
A static site generator should be your next language learning projectJohn Anderson
 
Old Dogs & New Tricks: What's New with Perl5 This Century
Old Dogs & New Tricks: What's New with Perl5 This CenturyOld Dogs & New Tricks: What's New with Perl5 This Century
Old Dogs & New Tricks: What's New with Perl5 This CenturyJohn Anderson
 
Introduction to Git (even for non-developers!)
Introduction to Git (even for non-developers!)Introduction to Git (even for non-developers!)
Introduction to Git (even for non-developers!)John Anderson
 
Introduction to Git for Non-Developers
Introduction to Git for Non-DevelopersIntroduction to Git for Non-Developers
Introduction to Git for Non-DevelopersJohn Anderson
 
A Modest Introduction To Swift
A Modest Introduction To SwiftA Modest Introduction To Swift
A Modest Introduction To SwiftJohn Anderson
 
A static site generator should be your next language learning project
A static site generator should be your next language learning projectA static site generator should be your next language learning project
A static site generator should be your next language learning projectJohn Anderson
 
Logs Are Magic: Why Git Workflows and Commit Structure Should Matter To You
Logs Are Magic: Why Git Workflows and Commit Structure Should Matter To YouLogs Are Magic: Why Git Workflows and Commit Structure Should Matter To You
Logs Are Magic: Why Git Workflows and Commit Structure Should Matter To YouJohn Anderson
 
JSON Web Tokens Will Improve Your Life
JSON Web Tokens Will Improve Your LifeJSON Web Tokens Will Improve Your Life
JSON Web Tokens Will Improve Your LifeJohn Anderson
 
Old Dogs & New Tricks: What's New With Perl5 This Century
Old Dogs & New Tricks: What's New With Perl5 This CenturyOld Dogs & New Tricks: What's New With Perl5 This Century
Old Dogs & New Tricks: What's New With Perl5 This CenturyJohn Anderson
 
A Modest Introduction to Swift
A Modest Introduction to SwiftA Modest Introduction to Swift
A Modest Introduction to SwiftJohn Anderson
 
Logs Are Magic: Why Git Workflows and Commit Structure Should Matter To You
Logs Are Magic: Why Git Workflows and Commit Structure Should Matter To YouLogs Are Magic: Why Git Workflows and Commit Structure Should Matter To You
Logs Are Magic: Why Git Workflows and Commit Structure Should Matter To YouJohn Anderson
 
Friends Don't Let Friends Browse Unencrypted: Running a VPN for friends and f...
Friends Don't Let Friends Browse Unencrypted: Running a VPN for friends and f...Friends Don't Let Friends Browse Unencrypted: Running a VPN for friends and f...
Friends Don't Let Friends Browse Unencrypted: Running a VPN for friends and f...John Anderson
 

Mehr von John Anderson (20)

#speakerlife
#speakerlife#speakerlife
#speakerlife
 
Introduction to Git (even for non-developers)
Introduction to Git (even for non-developers)Introduction to Git (even for non-developers)
Introduction to Git (even for non-developers)
 
Logs are-magic-devfestweekend2018
Logs are-magic-devfestweekend2018Logs are-magic-devfestweekend2018
Logs are-magic-devfestweekend2018
 
Logs Are Magic: Why Git Workflows and Commit Structure Should Matter To You
Logs Are Magic: Why Git Workflows and Commit Structure Should Matter To YouLogs Are Magic: Why Git Workflows and Commit Structure Should Matter To You
Logs Are Magic: Why Git Workflows and Commit Structure Should Matter To You
 
A static site generator should be your next language learning project
A static site generator should be your next language learning projectA static site generator should be your next language learning project
A static site generator should be your next language learning project
 
Do you want to be right or do you want to WIN?
Do you want to be right or do you want to WIN?Do you want to be right or do you want to WIN?
Do you want to be right or do you want to WIN?
 
An Introduction to Git (even for non-developers)
An Introduction to Git (even for non-developers)An Introduction to Git (even for non-developers)
An Introduction to Git (even for non-developers)
 
You got chocolate in my peanut butter! .NET on Mac & Linux
You got chocolate in my peanut butter! .NET on Mac & LinuxYou got chocolate in my peanut butter! .NET on Mac & Linux
You got chocolate in my peanut butter! .NET on Mac & Linux
 
A static site generator should be your next language learning project
A static site generator should be your next language learning projectA static site generator should be your next language learning project
A static site generator should be your next language learning project
 
Old Dogs & New Tricks: What's New with Perl5 This Century
Old Dogs & New Tricks: What's New with Perl5 This CenturyOld Dogs & New Tricks: What's New with Perl5 This Century
Old Dogs & New Tricks: What's New with Perl5 This Century
 
Introduction to Git (even for non-developers!)
Introduction to Git (even for non-developers!)Introduction to Git (even for non-developers!)
Introduction to Git (even for non-developers!)
 
Introduction to Git for Non-Developers
Introduction to Git for Non-DevelopersIntroduction to Git for Non-Developers
Introduction to Git for Non-Developers
 
A Modest Introduction To Swift
A Modest Introduction To SwiftA Modest Introduction To Swift
A Modest Introduction To Swift
 
A static site generator should be your next language learning project
A static site generator should be your next language learning projectA static site generator should be your next language learning project
A static site generator should be your next language learning project
 
Logs Are Magic: Why Git Workflows and Commit Structure Should Matter To You
Logs Are Magic: Why Git Workflows and Commit Structure Should Matter To YouLogs Are Magic: Why Git Workflows and Commit Structure Should Matter To You
Logs Are Magic: Why Git Workflows and Commit Structure Should Matter To You
 
JSON Web Tokens Will Improve Your Life
JSON Web Tokens Will Improve Your LifeJSON Web Tokens Will Improve Your Life
JSON Web Tokens Will Improve Your Life
 
Old Dogs & New Tricks: What's New With Perl5 This Century
Old Dogs & New Tricks: What's New With Perl5 This CenturyOld Dogs & New Tricks: What's New With Perl5 This Century
Old Dogs & New Tricks: What's New With Perl5 This Century
 
A Modest Introduction to Swift
A Modest Introduction to SwiftA Modest Introduction to Swift
A Modest Introduction to Swift
 
Logs Are Magic: Why Git Workflows and Commit Structure Should Matter To You
Logs Are Magic: Why Git Workflows and Commit Structure Should Matter To YouLogs Are Magic: Why Git Workflows and Commit Structure Should Matter To You
Logs Are Magic: Why Git Workflows and Commit Structure Should Matter To You
 
Friends Don't Let Friends Browse Unencrypted: Running a VPN for friends and f...
Friends Don't Let Friends Browse Unencrypted: Running a VPN for friends and f...Friends Don't Let Friends Browse Unencrypted: Running a VPN for friends and f...
Friends Don't Let Friends Browse Unencrypted: Running a VPN for friends and f...
 

Kürzlich hochgeladen

My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 

Kürzlich hochgeladen (20)

My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

Code Fast, Die Young, Throw Structured Exceptions

  • 1. Live Fast, Die Young, Leave A Good Looking Corpse
  • 2. Code Fast, die() Early, Throw Structured Exceptions
  • 3. Throw Structured Exceptions John SJ Anderson / @genehack / dc.pm YAPC::NA 2012 ~ Madison WI
  • 5. “Classic” Perl exceptions • Throw an exception with die()
  • 6. “Classic” Perl exceptions • Throw an exception with die() • Or Carp::croak(), Carp::confess(), etc.
  • 7. “Classic” Perl exceptions • Throw an exception with die() • Or Carp::croak(), Carp::confess(), etc. • TIMTOWTDI!
  • 8. “Classic” Perl exceptions • Throw an exception with die() • Or Carp::croak(), Carp::confess(), etc. • TIMTOWTDI! • Catch an exception with eval {}
  • 9. “Classic” Perl exceptions • Throw an exception with die() • Or Carp::croak(), Carp::confess(), etc. • TIMTOWTDI! • Catch an exception with eval {} • Handle an exception by looking at $@
  • 10. “Classic” Perl exception throwing 1 #! /usr/bin/perl 2 3 use strict; 4 use warnings; 5 6 eval { my $result = this_might_fail() }; 7 8 if( $@ ) { 9 # handle the error here 10 }
  • 11. Problems with “classic” Perl exceptions
  • 12. Problems with “classic” Perl exceptions • $@ can get clobbered
  • 13. Problems with “classic” Perl exceptions • $@ can get clobbered • $@ can get clobbered by code you don’t own
  • 14. Problems with “classic” Perl exceptions • $@ can get clobbered • $@ can get clobbered by code you don’t own • $@ might be a false value
  • 15. Problems with “classic” Perl exceptions • $@ can get clobbered • $@ can get clobbered by code you don’t own • $@ might be a false value • If $@ is a string, you’re depending on duplicated information, which will break.
  • 17. Use Try::Tiny for “semi-modern” Perl exceptions • Provides try{}/catch{}/finally{} blocks
  • 18. Use Try::Tiny for “semi-modern” Perl exceptions • Provides try{}/catch{}/finally{} blocks • Handles details of properly dealing with complexities around $@
  • 19. Use Try::Tiny for “semi-modern” Perl exceptions • Provides try{}/catch{}/finally{} blocks • Handles details of properly dealing with complexities around $@ • Lightweight and generally Just Works(tm).
  • 20. Use Try::Tiny for “semi-modern” Perl exceptions • Provides try{}/catch{}/finally{} blocks • Handles details of properly dealing with complexities around $@ • Lightweight and generally Just Works(tm). • N.b.: you have to end try{}/catch{} with a semicolon. Don’t forget this!
  • 21. Use Try::Tiny for “semi-modern” Perl exceptions 1 #! /usr/bin/perl 2 3 use strict; 4 use warnings; 5 6 use Try::Tiny; 7 8 try { 9 my $result = this_might_fail(); 10 } 11 catch { 12 # handle the error here 13 };
  • 22. Problems with “semi-modern” Perl exceptions • $@ can get clobbered • $@ can get clobbered by code you don’t own • $@ might be a false value • If $@ is a string, you’re depending on duplicated information, which will break.
  • 23. Problems with “semi-modern” Perl exceptions • If $@ is a string, you’re depending on duplicated information, which will break.
  • 24. Wait, where’s the duplicated information? 1 my $answer; 2 try { 3 # any of these might throw an exception 4 my $this = this_might_fail(); 5 my $that = something_else_might_fail(); 6 $answer = combine_them( $this , $that ); 7 } 8 catch { 9 # our error is in $_ 10 if( $_ =~ /some error/ ) { 11 # handle some error 12 } 13 elsif( $_ =~ /another error/ ) { 14 # handle another error 15 } 16 else { # not sure what the problem is, just give up 17 confess( $_ ); 18 } 19 };
  • 25. Wait, where’s the duplicated information? 1 my $answer; 2 try { 3 # any of these might throw an exception 4 my $this = this_might_fail(); 5 my $that = something_else_might_fail(); 6 $answer = combine_them( $this , $that ); 7 } 8 catch { 9 # our error is in $_ 10 if( $_ =~ /some error/ ) { 11 # handle some error 12 } 13 elsif( $_ =~ /another error/ ) { 14 # handle another error 15 } 16 else { # not sure what the problem is, just give up 17 confess( $_ ); 18 } 19 };
  • 26. Wait, where’s the duplicated information? • As soon as somebody “fixes” the string in some die() somewhere, you’ve potentially broken exception handling
  • 27. Wait, where’s the duplicated information? • As soon as somebody “fixes” the string in some die() somewhere, you’ve potentially broken exception handling • And you can’t even easily tell where, because it’s probably in a regexp that doesn’t look at all like the changed string
  • 28. Wait, where’s the duplicated information? • As soon as somebody “fixes” the string in some die() somewhere, you’ve potentially broken exception handling • And you can’t even easily tell where, because it’s probably in a regexp that doesn’t look at all like the changed string • Even if you have tests for the code in question, do you really have test coverage on all your exception cases?
  • 29. So what’s the solution?
  • 30. So what’s the solution? • die() can also take a reference as an argument
  • 31. So what’s the solution? • die() can also take a reference as an argument • So you can die() with an object!
  • 32. So what’s the solution? • die() can also take a reference as an argument • So you can die() with an object! • Which means you can cram all sorts of useful information into your exceptions
  • 33. So what’s the solution? • die() can also take a reference as an argument • So you can die() with an object! • Which means you can cram all sorts of useful information into your exceptions • And more importantly, handle them in a structured fashion that’s much less brittle than string comparisons
  • 34. A framework for structured exceptions: Exception::Class use Exception::Class (     'MyException',       'AnotherException' => { isa => 'MyException' },       'YetAnotherException' => {         isa         => 'AnotherException',         description => 'These exceptions are related to IPC'     },       'ExceptionWithFields' => {         isa    => 'YetAnotherException',         fields => [ 'grandiosity', 'quixotic' ],     }, );
  • 35. A framework for structured exceptions: Exception::Class # try eval { MyException->throw( error => 'I feel funny.' ) };   my $e;  # catch if ( $e = Exception::Class->caught('MyException') ) {     warn $e->error, "n", $e->trace->as_string, "n";     warn join ' ', $e->euid, $e->egid, $e->uid, $e->gid, $e->pid;     exit; } elsif ( $e = Exception::Class->caught('ExceptionWithFields') ) {     $e->quixotic ? do_something_wacky() : do_something_sane(); } else {     $e = Exception::Class->caught();     ref $e ? $e->rethrow : die $e; }
  • 37. Exception::Class Pros • Nice declarative syntax
  • 38. Exception::Class Pros • Nice declarative syntax • Possible to declare detailed or simple exception class hierarchies very simply
  • 39. Exception::Class Pros • Nice declarative syntax • Possible to declare detailed or simple exception class hierarchies very simply • Supports aliasing to make throwing particular exception types easier
  • 41. Exception::Class Cons • Not really designed for use with Try::Tiny
  • 42. Exception::Class Cons • Not really designed for use with Try::Tiny • Based on Class::Data::Inheritable, not Moose
  • 43. A Moose role for structured exceptions: Throwable package Redirect; use Moose; with 'Throwable';   has url => (is => 'ro'); ...then later... Redirect->throw({ url => $url });
  • 45. Throwable Pros • Implemented as a Moose role, so your exception classes are just normal Moose classes that consume the role
  • 46. Throwable Pros • Implemented as a Moose role, so your exception classes are just normal Moose classes that consume the role • So you get the usual Moose-y good stuff around attributes and methods and such.
  • 47. Throwable Pros • Implemented as a Moose role, so your exception classes are just normal Moose classes that consume the role • So you get the usual Moose-y good stuff around attributes and methods and such. • Comes with a grab-bag of typical exception behaviors (in Throwable::X), like stack traces, printf-ish messages, etc.
  • 50. Throwable Cons ? So far, I haven’t really found any.
  • 51. Throwable Cons ? So far, I haven’t really found any. (Of course, that doesn’t mean there aren’t any...)
  • 52. Error Handling Patterns & Anti-Patterns • DO use exceptions instead of error flags • DO throw exceptions as early as possible • DON’T catch exceptions unless you’re going to handle them – just let them propagate upwards • DO design your web application-level error actions to handle your business logic-level exceptions
  • 53. Use exceptions instead of error flags 1 sub some_catalyst_action :Local { 2 my( $self , $c ) = @_; 3 my $session = get_huge_session_object( $c->session ); 4 5 my $validated_params = validate_request_params( $c->request->params ) 6 or $c->detach( 'error' ); 7 8 my $step_one_result = $c->model('BusinessLogic')->do_step_one( $session , $validated_params ); 9 $c->detach( 'error' ) if $session->has_error(); 10 11 my $step_two_result = $c->model('BusinessLogic')->do_step_two( $step_one_result, $session ); 12 $c->detach( 'error' ) if $session->has_error(); 13 }
  • 54. Use exceptions instead of error flags Please please please don’t write code like this!
  • 55. Use exceptions instead of error flags
  • 56. Use exceptions instead of error flags • Forget just one of those checks and you’ve got a hard to track down bug
  • 57. Use exceptions instead of error flags • Forget just one of those checks and you’ve got a hard to track down bug • $session is being passed just to provide access to that error flag.
  • 58. Use exceptions instead of error flags • Forget just one of those checks and you’ve got a hard to track down bug • $session is being passed just to provide access to that error flag. • The error action gets no real info about what the problem was, or it tries to pull it from $session itself (which has its own problems)
  • 59. Use exceptions instead of error flags 1 sub some_catalyst_action :Local { 2 my( $self , $c ) = @_; 3 4 try { 5 my $validated_params = validate_request_params( $c->request->params ) 6 7 my $step_one_result = $c->model('BusinessLogic')->do_step_one( $session , $validated_params ); 8 9 my $step_two_result = $c->model('BusinessLogic')->do_step_two( $step_one_result, $session ); 10 } 11 catch { $c->detach( 'error' , [ $_ ] ) }; 12 }
  • 60. Throw exceptions as early as possible
  • 61. Throw exceptions as early as possible • If you’re going to throw an exception because you didn’t get passed something, do it ASAP.
  • 62. Throw exceptions as early as possible • If you’re going to throw an exception because you didn’t get passed something, do it ASAP. • In general, the quicker you can die(), the better – because it reduces the amount of code that might contain the bug.
  • 64. Don’t catch exceptions except to handle them • Most of the time, your business logic code is going to throw exceptions, not catch them
  • 65. Don’t catch exceptions except to handle them • Most of the time, your business logic code is going to throw exceptions, not catch them • If you do catch an exception, you should be trying to fix the problem.
  • 66. Don’t catch exceptions except to handle them • Most of the time, your business logic code is going to throw exceptions, not catch them • If you do catch an exception, you should be trying to fix the problem. • Don’t catch exceptions just to munge them or log them and re-throw them. Munge them or log them before you throw them.
  • 67. Further reading • Throwable::X: common behavior for thrown exceptions (<http://rjbs.manxome.org/rubric/entry/1860>) • Exceptionally Extensible Exceptions (<http://advent.rjbs.manxome.org/2010/2010-12-03.html>) • Structured Data and Knowing versus Guessing (<http://www.modernperlbooks.com/mt/2010/10/structured-data-and-knowing-versus-guessing.html>)
  • 69. Further reading • Throwable::X: common behavior for thrown exceptions (<http://rjbs.manxome.org/rubric/entry/1860>) • Exceptionally Extensible Exceptions (<http://advent.rjbs.manxome.org/2010/2010-12-03.html>) • Structured Data and Knowing versus Guessing (<http://www.modernperlbooks.com/mt/2010/10/structured-data-and-knowing-versus-guessing.html>)

Hinweis der Redaktion

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n