Best practices for handling ActiveRecord exceptions

A co-worker recently suggested that I stop using ActiveRecord’s find( ) method,
and instead should use find_by( ) since it won’t throw an exception.
This brings to mind a few questions:

  1. Is it better to use find_by( ), rather than find( ) ?

  2. If find( ) is preferred, are exceptions caught at some other place (like ApplicationController)? I rarely see code with find( ) wrapped inside a begin/rescue block so something must be dealing with the exception. Or are default Rails error pages the common way of dealing with this? Perhaps custom error pages?

  3. Are there any recommended gems for dealing with ActiveRecord exceptions and how to report/display to the user?

  1. find is normally used when looking up record by its primary key, e.g. you view a list of products then click on one product to see more details. If the particular record can’t be found, that’s usually an indication that something is wrong, so an exception is raised.

In some situations it might be appropriate to use find_by. The main problem is that find_by will return nil when there are no matches, and passing nils around can often result in painful bugs (see this post).

  1. find will raise a ActiveRecord::RecordNotFound, which by default Rails will catch at the controller level and render a 404 Not Found page. This behaviour can be changed, but it’s probably unwise to.

  2. Not that I know of. This kind of behaviour is usually quite specific to the application being built.