Skip to content

Instantly share code, notes, and snippets.

@danielpaul
Created August 18, 2020 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielpaul/f53ff9674cfed210e78b56dc598e0cc5 to your computer and use it in GitHub Desktop.
Save danielpaul/f53ff9674cfed210e78b56dc598e0cc5 to your computer and use it in GitHub Desktop.
Rails API Controller Error Handling Pattern
class AnythingController < ApiController
def index
raise ApiError.new("My custom message", 401)
end
end
class ApiController < ActionController::Base
rescue_from ApiError do |exception|
render json: Api::V1::ResponseService.error!(exception.message, exception.status_code)
end
end
class ApiError < StandardError
def initialize(message="API Error", error_code=500)
@error_code = error_code
super(message)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment