0
0
RailsDebug / FixBeginner · 3 min read

How to Handle Errors in Controller in Ruby on Rails

In Ruby on Rails controllers, handle errors by using rescue_from to catch exceptions and respond gracefully. You can also use begin-rescue-end blocks inside actions to manage specific errors and render appropriate responses.
🔍

Why This Happens

When an error occurs in a Rails controller action and is not handled, the application raises an exception that leads to a server error (500) or an unhelpful error page. This happens because the controller does not catch the error, so Rails shows a generic error response.

ruby
class UsersController < ApplicationController
  def show
    @user = User.find(params[:id])
    # If user not found, this raises ActiveRecord::RecordNotFound
  end
end
Output
ActiveRecord::RecordNotFound (Couldn't find User with 'id'=123)
🔧

The Fix

Use rescue_from in the controller to catch exceptions like ActiveRecord::RecordNotFound and render a friendly error page or JSON response. Alternatively, use begin-rescue-end inside actions for specific error handling.

ruby
class UsersController < ApplicationController
  rescue_from ActiveRecord::RecordNotFound, with: :user_not_found

  def show
    @user = User.find(params[:id])
  end

  private

  def user_not_found
    render plain: "User not found", status: :not_found
  end
end
Output
When user not found, response is: "User not found" with HTTP status 404
🛡️

Prevention

Always anticipate possible errors in controller actions and handle them using rescue_from or begin-rescue-end. Use meaningful HTTP status codes and user-friendly messages. Keep error handling DRY by placing common handlers in ApplicationController. Use Rails logging to track errors and test error scenarios.

⚠️

Related Errors

  • ActionController::ParameterMissing: Handle missing required parameters with rescue_from ActionController::ParameterMissing.
  • ActiveRecord::RecordInvalid: Catch validation errors when saving records and respond with error messages.
  • RoutingError: Handle unknown routes gracefully in ApplicationController.

Key Takeaways

Use rescue_from in controllers to catch and handle exceptions globally.
Render clear error messages with appropriate HTTP status codes.
Keep error handling DRY by defining handlers in ApplicationController.
Test error cases to ensure your app responds gracefully.
Use begin-rescue-end blocks for action-specific error handling.