Error Handling in Ruby on Rails Applications

Introduction

Welcome to the lesson on error handling in Ruby on Rails applications. In previous lessons, we integrated a database, added a column to the todos table, and configured middleware to enhance our application's security. Now, we’ll focus on handling errors gracefully to ensure our application provides meaningful feedback to users when things go wrong.

Error handling is crucial in enterprise applications. It helps maintain a smooth user experience by properly managing and displaying errors. By the end of this lesson, you will learn to implement a custom exception handler that catches and manages common errors in your Rails application. Let's get started!

Introduction to Exception Handling in Rails

Ruby on Rails provides built-in mechanisms to handle exceptions gracefully. One powerful tool is the rescue_from method, which allows us to specify how to handle specific exceptions in our controller.

Here’s a simple example of how rescue_from works:

Ruby
class TodosController < ApplicationController
  rescue_from ActiveRecord::RecordNotFound, with: :record_not_found

  def show
    @todo = Todo.find(params[:id])
    render json: @todo
  end

  private

  def record_not_found(exception)
    render json: { error: exception.message }, status: :not_found
  end
end

In this code, when an ActiveRecord::RecordNotFound exception is raised, the record_not_found method is called, which renders a JSON response with an error message and a 404 Not Found status.

Implementing a Custom Exception Handler

To handle exceptions more elegantly across multiple controllers, we can create a Concern for exception handling. Concerns use ActiveSupport::Concern, which simplifies the inclusion of shared behavior in Rails controllers:

Ruby
module ExceptionHandler
  extend ActiveSupport::Concern

  included do
    rescue_from ActiveRecord::RecordNotFound do |e|
      render json: { error: e.message }, status: :not_found
    end

    rescue_from ActiveRecord::RecordInvalid, with: :unprocessable_entity_response
  end

  private

  def unprocessable_entity_response(exception)
    render json: { error: exception.message }, status: :unprocessable_entity
  end
end

This ExceptionHandler module uses rescue_from to handle two common exceptions: ActiveRecord::RecordNotFound and ActiveRecord::RecordInvalid. The unprocessable_entity_response method provides customized error responses for invalid records.

  • ActiveSupport::Concern: This module is used to create reusable concerns in Rails. It provides methods for including functionality in a modular way.
  • rescue_from: This method specifies how to handle exceptions in controllers. In our example, it handles ActiveRecord::RecordNotFound by rendering a JSON error message with a 404 status. It also handles ActiveRecord::RecordInvalid using the unprocessable_entity_response method.
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal