How to Handle Errors in Controller in Ruby on Rails
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.
class UsersController < ApplicationController def show @user = User.find(params[:id]) # If user not found, this raises ActiveRecord::RecordNotFound end end
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.
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
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.