0
0
RailsDebug / FixBeginner · 4 min read

How to Handle API Errors in Rails: Best Practices and Examples

In Rails, handle API errors by using 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.

ruby
class UsersController < ApplicationController
  def show
    user = User.find(params[:id])
    render json: user
  end
end
Output
ActiveRecord::RecordNotFound (Couldn't find User with 'id'=123) Response: HTML 404 error page
🔧

The 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.

ruby
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
Output
{ "error": "Couldn't find User with 'id'=123" } with HTTP status 404
🛡️

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::RecordInvalid to catch validation failures and return 422 status with error details.
  • Parameter Missing: Handle ActionController::ParameterMissing to notify clients about missing required parameters.
  • Unauthorized Access: Rescue Pundit::NotAuthorizedError or similar to return 401 or 403 status codes.

Key Takeaways

Use rescue_from in controllers to catch exceptions and return JSON error responses.
Return meaningful error messages with correct HTTP status codes like 404 or 422.
Inherit from ActionController::API for API-only controllers to avoid HTML responses.
Test your API error handling to ensure clients receive consistent feedback.
Handle common errors like RecordNotFound, RecordInvalid, and ParameterMissing explicitly.