Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Ruby Exceptions

Martin
November 07, 2015

Ruby Exceptions

Something about Ruby Exceptions

Martin

November 07, 2015
Tweet

More Decks by Martin

Other Decks in Programming

Transcript

  1. OVERVIEW 1. An Simple Example 2. Why Exceptions 3. How

    To Raise Exception 4. How To Rescue Exception 5. Real Cases 6. Talk With Our Projects 7. Conclusions 8. Some Tips
  2. WHY EXCEPTIONS • More clear error messages
 AuthenticationError: ‘token invalide’

    v.s. ‘your token is invalid’ • Can be used to block unnecessary further more operations • Forced
 A developer can ignore (or not be aware of) your return status and go on blissfully unaware that something failed.
 Exception can't be silently ignored.
  3. HOW TO RAISE AN ERROR • Simpliest - just use

    `raise` (RuntimeError) • Raise with specified type of exception
 e.g. `raise App::AuthenticationFailedError, ‘token is invalid’`
 
 Note: Remember to define your own errors
  4. HOW TO RESCUE FROM ERROR(S) • Simpliest - just use

    `rescue` (StandardError, almost all usual exceptions) • Rescue specified type of exception • Rescue a exception • Rescue multiple exceptions parallelism • Use `retry` and `ensure`
  5. REAL CASES • Exception Notification
 rubygem: exception_notification • Provide a

    complete exceptions mechanism • Validate user input (ArgumentError) • Detect other errors: Network, system environment, etc...
  6. FROM OUR PROJECTS • StateMachine: use `object.event!`, instead of `object.event`


    the former will raise error if transition failed, so we can handle AEAP • Communication between different layers(M v.s. C)
 If you need to display error messages to users, you should use flash, but flash is existed at controller layer.
  7. CONCLUSIONS • Exception is not evil • Remember to rescue

    exceptions • Provide exceptions mechanism if you are developing a gem
  8. SOME TIPS • It is to be noted that the

    body of a method definition is an implicit begin-end block • Be careful to rescue `Exception` • A library should have one subclass of StandardError or RuntimeError and have specific exception types inherit from it
  9. WHY NOT RESCUE `EXCEPTION` • Exception is the root of

    Ruby's exception hierarchy, so when you rescue Exception you rescue from everything • Exceptions to events map: • Interrupt => Ctrl + C • SignalException => kill -9 • SyntaxError
  10. WHY RESCUE `EXCEPTION` • One of the few common cases

    where it’s sane to rescue from Exception is for logging/reporting purposes, in which case you should immediately re-raise the exception