SlideShare une entreprise Scribd logo
1  sur  76
Live Fast,
        Die Young,
Have A Good Looking Corpse
Code Fast,
       die() Early,
Throw Structured Exceptions
Throw Structured Exceptions
         John SJ Anderson
            @genehack
            03 Jan 2012
“Classic” Perl exception throwing
“Classic” Perl exception throwing
•   Throw an exception with die()
“Classic” Perl exception throwing
•   Throw an exception with die()

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

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

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

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

•   TIMTOWTDI!

•   Catch an exception with eval {}
“Classic” Perl exception throwing
•   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   }
11
12   sub this_might_fail {
13     die "FAILED!"
14       if rand() < 0.5;
15   }
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   };
14
15   sub this_might_fail {
16     die "FAILED!"
17       if rand() < 0.5;
18   }
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?

• Even if you have tests for the code in question, do you
  really have test coverage on all your exception cases?
Wait, where’s the duplicated information?

• Even if you have tests for the code in question, do you
  really have test coverage on all your exception cases?
• (Almost certainly not. If you do, come write tests for
  $WORK_PROJECT, we need the help...)
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 macro definitions 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
Error Handling
          Patterns & Anti-Patterns
• DO use exceptions instead of error flags
Error Handling
          Patterns & Anti-Patterns
• DO use exceptions instead of error flags
• DO throw exceptions as early as possible
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
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
14   $c->stash({
15     one => $step_one_result ,
16     two => $step_two_result ,
17   });
18 }
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

•   Many times, $session was passed just to provide access to that
    error flag. Far too much information was being passed around for
    no reason
Use exceptions instead of error flags
•   Forget just one of those checks and you’ve got a hard to track down
    bug

•   Many times, $session was passed just to provide access to that
    error flag. Far too much information was being passed around for
    no reason

•   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
13   $c->stash({
14     one => $step_one_result ,
15     two => $step_two_result ,
16   });
17 }
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.
Web application error actions
 should handle exceptions
 1 sub error :Private {
 2   my( $self , $c , $error ) = @_;
 3
 4   my $message = 'An unexpected error happened.';
 5
 6   # NOTE: duck typing
 7   $message = $error->user_visible_message
 8     if( $error->has_user_visible_message and ! $error->is_private );
 9
10   $c->stash({
11       message => $message ,
12       template => 'error',
13   });
14 }
Web application error actions
 should handle exceptions
 1 sub error :Private {
 2   my( $self , $c , $error ) = @_;
 3
 4   my $message = 'An unexpected error happened.';
 5
 6   # NOTE: duck typing
 7   $message = $error->user_visible_message
 8     if( $error->has_user_visible_message and ! $error->is_private );
 9
10   $c->stash({
11       message => $message ,
12       template => 'error',
13   });
14 }


                  (again, not the best example ever...)
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 for your time
    this evening!
Questions?

Contenu connexe

En vedette

Криокомплекс
КриокомплексКриокомплекс
Криокомплексkulibin
 
Keith hopper-product-market-fit
Keith hopper-product-market-fitKeith hopper-product-market-fit
Keith hopper-product-market-fithopperomatic
 
正向積極成功學
正向積極成功學正向積極成功學
正向積極成功學yourwater
 
Сектор_НИТ_отдела_Технического_творчества_МГДД(Ю)Т
Сектор_НИТ_отдела_Технического_творчества_МГДД(Ю)ТСектор_НИТ_отдела_Технического_творчества_МГДД(Ю)Т
Сектор_НИТ_отдела_Технического_творчества_МГДД(Ю)ТIvan Dementiev
 
Social media strategies for dr. pfahl class, 8 13
Social media strategies for dr. pfahl class, 8 13Social media strategies for dr. pfahl class, 8 13
Social media strategies for dr. pfahl class, 8 13Game Day Communications
 
Hidden gluteninthankgivingmeal
Hidden gluteninthankgivingmealHidden gluteninthankgivingmeal
Hidden gluteninthankgivingmealGlutagest
 
АВтоматизированный Расчет Операционных РАзмеров
АВтоматизированный Расчет Операционных РАзмеровАВтоматизированный Расчет Операционных РАзмеров
АВтоматизированный Расчет Операционных РАзмеровkulibin
 
5 Things Everyone Should Know about Low-Calorie Sweeteners
5 Things Everyone Should Know about Low-Calorie Sweeteners5 Things Everyone Should Know about Low-Calorie Sweeteners
5 Things Everyone Should Know about Low-Calorie SweetenersFood Insight
 
מצגת כיתה ט
מצגת כיתה טמצגת כיתה ט
מצגת כיתה טguest27a22b
 
Система передачи субмиллиметровых биологических сигналов
Система передачи субмиллиметровых биологических  сигналовСистема передачи субмиллиметровых биологических  сигналов
Система передачи субмиллиметровых биологических сигналовkulibin
 
Ipsos MORI Scotland Opinion Monitor - Lockerbie - October 2011
Ipsos MORI Scotland Opinion Monitor - Lockerbie - October 2011Ipsos MORI Scotland Opinion Monitor - Lockerbie - October 2011
Ipsos MORI Scotland Opinion Monitor - Lockerbie - October 2011Ipsos UK
 
Apresentando ideias com Prezi
Apresentando ideias com PreziApresentando ideias com Prezi
Apresentando ideias com PreziMarcio Okabe
 

En vedette (16)

Криокомплекс
КриокомплексКриокомплекс
Криокомплекс
 
Keith hopper-product-market-fit
Keith hopper-product-market-fitKeith hopper-product-market-fit
Keith hopper-product-market-fit
 
正向積極成功學
正向積極成功學正向積極成功學
正向積極成功學
 
Сектор_НИТ_отдела_Технического_творчества_МГДД(Ю)Т
Сектор_НИТ_отдела_Технического_творчества_МГДД(Ю)ТСектор_НИТ_отдела_Технического_творчества_МГДД(Ю)Т
Сектор_НИТ_отдела_Технического_творчества_МГДД(Ю)Т
 
Social media strategies for dr. pfahl class, 8 13
Social media strategies for dr. pfahl class, 8 13Social media strategies for dr. pfahl class, 8 13
Social media strategies for dr. pfahl class, 8 13
 
Hidden gluteninthankgivingmeal
Hidden gluteninthankgivingmealHidden gluteninthankgivingmeal
Hidden gluteninthankgivingmeal
 
Managing risk in challenging economic times
Managing risk in challenging economic timesManaging risk in challenging economic times
Managing risk in challenging economic times
 
АВтоматизированный Расчет Операционных РАзмеров
АВтоматизированный Расчет Операционных РАзмеровАВтоматизированный Расчет Операционных РАзмеров
АВтоматизированный Расчет Операционных РАзмеров
 
Mi primer dibujo
Mi primer dibujoMi primer dibujo
Mi primer dibujo
 
5 Things Everyone Should Know about Low-Calorie Sweeteners
5 Things Everyone Should Know about Low-Calorie Sweeteners5 Things Everyone Should Know about Low-Calorie Sweeteners
5 Things Everyone Should Know about Low-Calorie Sweeteners
 
מצגת כיתה ט
מצגת כיתה טמצגת כיתה ט
מצגת כיתה ט
 
Curation Nation
Curation Nation Curation Nation
Curation Nation
 
Система передачи субмиллиметровых биологических сигналов
Система передачи субмиллиметровых биологических  сигналовСистема передачи субмиллиметровых биологических  сигналов
Система передачи субмиллиметровых биологических сигналов
 
Ipsos MORI Scotland Opinion Monitor - Lockerbie - October 2011
Ipsos MORI Scotland Opinion Monitor - Lockerbie - October 2011Ipsos MORI Scotland Opinion Monitor - Lockerbie - October 2011
Ipsos MORI Scotland Opinion Monitor - Lockerbie - October 2011
 
Apresentando ideias com Prezi
Apresentando ideias com PreziApresentando ideias com Prezi
Apresentando ideias com Prezi
 
Innovations New World Order
Innovations New World OrderInnovations New World Order
Innovations New World Order
 

Similaire à Code Fast, die() Early, Throw Structured Exceptions

Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation TutorialLorna Mitchell
 
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
 
Section 8 Programming Style and Your Brain: Douglas Crockford
Section 8 Programming Style and Your Brain: Douglas CrockfordSection 8 Programming Style and Your Brain: Douglas Crockford
Section 8 Programming Style and Your Brain: Douglas Crockfordjaxconf
 
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
 
Douglas Crockford - Programming Style and Your Brain
Douglas Crockford - Programming Style and Your BrainDouglas Crockford - Programming Style and Your Brain
Douglas Crockford - Programming Style and Your BrainWeb Directions
 
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)Alex Balhatchet
 
Red Flags in Programming
Red Flags in ProgrammingRed Flags in Programming
Red Flags in ProgrammingxSawyer
 
Introduction to writing readable and maintainable Perl
Introduction to writing readable and maintainable PerlIntroduction to writing readable and maintainable Perl
Introduction to writing readable and maintainable PerlAlex Balhatchet
 
Exception+Logging=Diagnostics 2011
Exception+Logging=Diagnostics 2011Exception+Logging=Diagnostics 2011
Exception+Logging=Diagnostics 2011Paulo Gaspar
 
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
 
Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Wen-Tien Chang
 
perl 6 hands-on tutorial
perl 6 hands-on tutorialperl 6 hands-on tutorial
perl 6 hands-on tutorialmustafa sarac
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technologyppparthpatel123
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersGiovanni924
 

Similaire à Code Fast, die() Early, Throw Structured Exceptions (20)

Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
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)?
 
Section 8 Programming Style and Your Brain: Douglas Crockford
Section 8 Programming Style and Your Brain: Douglas CrockfordSection 8 Programming Style and Your Brain: Douglas Crockford
Section 8 Programming Style and Your Brain: Douglas Crockford
 
Code with style
Code with styleCode with style
Code with style
 
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
 
Douglas Crockford - Programming Style and Your Brain
Douglas Crockford - Programming Style and Your BrainDouglas Crockford - Programming Style and Your Brain
Douglas Crockford - Programming Style and Your Brain
 
Ruby Gotchas
Ruby GotchasRuby Gotchas
Ruby Gotchas
 
Ruby Gotchas
Ruby GotchasRuby Gotchas
Ruby Gotchas
 
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)
 
Red Flags in Programming
Red Flags in ProgrammingRed Flags in Programming
Red Flags in Programming
 
Introduction to writing readable and maintainable Perl
Introduction to writing readable and maintainable PerlIntroduction to writing readable and maintainable Perl
Introduction to writing readable and maintainable Perl
 
Exception+Logging=Diagnostics 2011
Exception+Logging=Diagnostics 2011Exception+Logging=Diagnostics 2011
Exception+Logging=Diagnostics 2011
 
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)
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介
 
perl 6 hands-on tutorial
perl 6 hands-on tutorialperl 6 hands-on tutorial
perl 6 hands-on tutorial
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technology
 
Perl Moderno
Perl ModernoPerl Moderno
Perl Moderno
 
Modern Perl
Modern PerlModern Perl
Modern Perl
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammers
 

Plus de 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
 

Plus de 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...
 

Dernier

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 

Dernier (20)

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 

Code Fast, die() Early, Throw Structured Exceptions

  • 1. Live Fast, Die Young, Have A Good Looking Corpse
  • 2. Code Fast, die() Early, Throw Structured Exceptions
  • 3. Throw Structured Exceptions John SJ Anderson @genehack 03 Jan 2012
  • 5. “Classic” Perl exception throwing • Throw an exception with die()
  • 6. “Classic” Perl exception throwing • Throw an exception with die() • Or Carp::croak(), Carp::confess(), etc.
  • 7. “Classic” Perl exception throwing • Throw an exception with die() • Or Carp::croak(), Carp::confess(), etc. • TIMTOWTDI!
  • 8. “Classic” Perl exception throwing • Throw an exception with die() • Or Carp::croak(), Carp::confess(), etc. • TIMTOWTDI! • Catch an exception with eval {}
  • 9. “Classic” Perl exception throwing • 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 12 sub this_might_fail { 13 die "FAILED!" 14 if rand() < 0.5; 15 }
  • 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 }; 14 15 sub this_might_fail { 16 die "FAILED!" 17 if rand() < 0.5; 18 }
  • 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? • Even if you have tests for the code in question, do you really have test coverage on all your exception cases?
  • 29. Wait, where’s the duplicated information? • Even if you have tests for the code in question, do you really have test coverage on all your exception cases? • (Almost certainly not. If you do, come write tests for $WORK_PROJECT, we need the help...)
  • 30. So what’s the solution?
  • 31. So what’s the solution? • die() can also take a reference as an argument
  • 32. So what’s the solution? • die() can also take a reference as an argument • So you can die() with an object!
  • 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
  • 34. 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
  • 35. 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' ],     }, );
  • 36. 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; }
  • 38. Exception::Class Pros • Nice declarative syntax
  • 39. Exception::Class Pros • Nice declarative syntax • Possible to declare detailed or simple exception class hierarchies very simply
  • 40. Exception::Class Pros • Nice declarative syntax • Possible to declare detailed or simple exception class hierarchies very simply • Supports macro definitions to make throwing particular exception types easier
  • 42. Exception::Class Cons • Not really designed for use with Try::Tiny
  • 43. Exception::Class Cons • Not really designed for use with Try::Tiny • Based on Class::Data::Inheritable, not Moose
  • 44. A Moose role for structured exceptions: Throwable package Redirect; use Moose; with 'Throwable';   has url => (is => 'ro'); ...then later... Redirect->throw({ url => $url });
  • 46. Throwable Pros • Implemented as a Moose role, so your exception classes are just normal Moose classes that consume the role
  • 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.
  • 48. 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.
  • 51. Throwable Cons ? So far, I haven’t really found any.
  • 52. Throwable Cons ? So far, I haven’t really found any. (Of course, that doesn’t mean there aren’t any...)
  • 53. Error Handling Patterns & Anti-Patterns
  • 54. Error Handling Patterns & Anti-Patterns • DO use exceptions instead of error flags
  • 55. Error Handling Patterns & Anti-Patterns • DO use exceptions instead of error flags • DO throw exceptions as early as possible
  • 56. 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
  • 57. 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
  • 58. 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 14 $c->stash({ 15 one => $step_one_result , 16 two => $step_two_result , 17 }); 18 }
  • 59. Use exceptions instead of error flags Please please please don’t write code like this!
  • 60. Use exceptions instead of error flags
  • 61. Use exceptions instead of error flags • Forget just one of those checks and you’ve got a hard to track down bug
  • 62. Use exceptions instead of error flags • Forget just one of those checks and you’ve got a hard to track down bug • Many times, $session was passed just to provide access to that error flag. Far too much information was being passed around for no reason
  • 63. Use exceptions instead of error flags • Forget just one of those checks and you’ve got a hard to track down bug • Many times, $session was passed just to provide access to that error flag. Far too much information was being passed around for no reason • 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)
  • 64. 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 13 $c->stash({ 14 one => $step_one_result , 15 two => $step_two_result , 16 }); 17 }
  • 65. Throw exceptions as early as possible
  • 66. Throw exceptions as early as possible • If you’re going to throw an exception because you didn’t get passed something, do it ASAP.
  • 67. 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.
  • 69. Don’t catch exceptions except to handle them • Most of the time, your business logic code is going to throw exceptions, not catch them
  • 70. 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.
  • 71. 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.
  • 72. Web application error actions should handle exceptions 1 sub error :Private { 2 my( $self , $c , $error ) = @_; 3 4 my $message = 'An unexpected error happened.'; 5 6 # NOTE: duck typing 7 $message = $error->user_visible_message 8 if( $error->has_user_visible_message and ! $error->is_private ); 9 10 $c->stash({ 11 message => $message , 12 template => 'error', 13 }); 14 }
  • 73. Web application error actions should handle exceptions 1 sub error :Private { 2 my( $self , $c , $error ) = @_; 3 4 my $message = 'An unexpected error happened.'; 5 6 # NOTE: duck typing 7 $message = $error->user_visible_message 8 if( $error->has_user_visible_message and ! $error->is_private ); 9 10 $c->stash({ 11 message => $message , 12 template => 'error', 13 }); 14 } (again, not the best example ever...)
  • 74. 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>)
  • 75. Thanks for your time this evening!

Notes de l'éditeur

  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
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n