Created
August 18, 2020 14:55
-
-
Save danielpaul/f53ff9674cfed210e78b56dc598e0cc5 to your computer and use it in GitHub Desktop.
Rails API Controller Error Handling Pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AnythingController < ApiController | |
def index | |
raise ApiError.new("My custom message", 401) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ApiController < ActionController::Base | |
rescue_from ApiError do |exception| | |
render json: Api::V1::ResponseService.error!(exception.message, exception.status_code) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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