DEV Community

Discussion on: Custom Exceptions in Ruby

Collapse
 
michaelglass profile image
Michael Glass • Edited

Writing literate exceptions is great advice! I'm certainly guilty of wrapping everything in a simple RunTimeError with raise "here's what happened, bub!".

However, I'm wary of the recommendation in this article about using literate errors as an alternate to existing control flow.

Exceptions have the special property of throwing until caught. Unlike other control flow, exceptions need to be caught. If you're planning on catching something in the caller, it's probably good to use control flow that doesn't re-raise.

If you're planning on catching something in the caller of the caller, it's probably a good idea to refactor your code so you're not zipping back and forth between multiple layers. E.g. if you're always going to catch something two levels down, using an exception as a fancy "GOTO" makes reasoning about what's going on quite difficult.

There's a lot written about this "sometimes anti-pattern". Maybe most famously wiki.c2.com/?DontUseExceptionsForF...

Here's an attempt to handle the same situation with explicit control flow, e.g. maybe a case statement.

def upload
  @image = params[:image]

  case ImageHandler.handle_upload(@image)
  when :success
    redirect_to :index, :notice => "Image upload success!"
  when :wrong_dimensions
    render "edit", :alert => "Error: #{wrong_dimension_message(@image)}"
  when :wrong_extension
    head :forbidden
  end
end

In this case, we know that handle_upload is local, expected edges are handled locally, and unexpected edges are thrown (as they should).

Collapse
 
matsimitsu profile image
Robert Beekman

Hi Michael, thanks for your excellent suggestion. I've discussed this while writing the article with my colleagues and we came to the same conclusion.

I still went ahead with the current example, because it's compact, easily understandable and covers all the scenarios I wanted to explain. I'm planning to write another article that covers the "anti-pattern" you rightfully raised.