DEV Community

critwitt
critwitt

Posted on

Handling Errors in Ruby

When working with Active Record within Ruby, utilizing CRUD operations can yield a multitude of errors. Some common errors are ActiveRecord::RecordNotFound, ActiveRecord::RecordInvalid, and ActiveRecord::InvalidForeignKey among others. In this blog, we're going to go over some ways in which you can handle these errors in order to give the user more information about the errors they receive.

Utilizing rescue_from

A recommended way for error handling is utilizing Ruby's built in rescue_from instance public method. Able to be placed right in your ApplicationController or in any specific class controller, rescue_from in combination with a trailing :with option allows for you to create a private method to handle errors.

class ApplicationController < ActionController::Base
  rescue_from User::RecordNotFound, with: :not_found

  private

  def not_found
    render json: {error: "Record not found"}
  end
end
Enter fullscreen mode Exit fullscreen mode

This will render an error message to the user indicating that the record they were searching for does not exist. This can take care of some errors with #show and #destroy methods. But what if we're creating a new instance but our user does not pass our data validations? Wouldn't it be nice to tell our user what validations were not passed? Let's explore how we can handle that in our next section

Handling Validations Errors

There's an important decision you have to make when creating data, and that's whether you want to use create or create!. Comparing the two, create returns the object created by the user, while create! returns a RecordInvalid error.

create

class InstanceController < ApplicationController

  def create
    instance = InstanceClass.create(instance_params)
    if instance.valid?
      render json: instance, status: :created
    else
      render json: {errors: instance.errors }, status: :unprocessable_entity
      end
  end
end
Enter fullscreen mode Exit fullscreen mode

Using create allows for a user to access the errors key to display all the errors associated with the object.

create!

class InstanceController < ApplicationController

  rescue_from ActiveRecord::RecordInvalid, with: :invalid

  def create
    instance = Instance.create!(instance_params)
    render json: instance, status: :created
  end

  private

  def invalid errors
    render json: {errors: errors}, status: :unprocessable_entity
  end
end
Enter fullscreen mode Exit fullscreen mode

Here we can see that create! will raise a RecordInvalid error, and that will be rendered for each invalid option. So that takes care of #create errors in terms of validation.

Using this guide, play around with Active Record and Postman and see if you can generate and debug your own errors. Happy Coding!

Top comments (0)