How to Handle API Errors in Rails: Best Practices and Examples
rescue_from in your controllers to catch exceptions and return JSON error responses with appropriate HTTP status codes. This approach keeps your API responses clear and consistent for clients.Why This Happens
When an API request causes an error like a record not found or invalid data, Rails by default raises exceptions that return HTML error pages. This breaks API clients expecting JSON and causes confusion.
class UsersController < ApplicationController
def show
user = User.find(params[:id])
render json: user
end
endThe Fix
Use rescue_from in your controller or ApplicationController to catch exceptions like ActiveRecord::RecordNotFound and return a JSON error message with a proper HTTP status code. This makes your API responses consistent and easy to handle.
class ApplicationController < ActionController::API rescue_from ActiveRecord::RecordNotFound, with: :record_not_found private def record_not_found(exception) render json: { error: exception.message }, status: :not_found end end class UsersController < ApplicationController def show user = User.find(params[:id]) render json: user end end
Prevention
Always handle common exceptions in your API controllers using rescue_from. Return clear JSON error messages with appropriate HTTP status codes like 404 for not found or 422 for validation errors. Use ActionController::API for lightweight API-only controllers. Test your error responses to ensure clients get consistent feedback.
Related Errors
- Validation Errors: Use
rescue_from ActiveRecord::RecordInvalidto catch validation failures and return 422 status with error details. - Parameter Missing: Handle
ActionController::ParameterMissingto notify clients about missing required parameters. - Unauthorized Access: Rescue
Pundit::NotAuthorizedErroror similar to return 401 or 403 status codes.