-
-
Save trantuanckc/3b05871de121bfae8a56b9e35cda8232 to your computer and use it in GitHub Desktop.
grape error handling
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
# app/controllers/api/v1.rb | |
class Api::V1 < Grape::API | |
class Grape::Middleware::Error | |
def error_message(code, text) | |
{ | |
:error => { | |
:code => code, | |
:message => text | |
} | |
}.to_json | |
end | |
end | |
rescue_from Api::V1::BaseAPI::InvalidToken do |e| | |
rack_response(error_message(50, 'invalid access token provided'), 401) | |
end | |
rescue_from Api::V1::BaseAPI::AccessDenied do |e| | |
rack_response(error_message(60, 'access denied'), 403) | |
end | |
rescue_from ActiveRecord::RecordNotFound do |e| | |
rack_response(error_message(70, 'not found'), 404) | |
end | |
rescue_from Grape::Exceptions::ValidationErrors do |e| | |
rack_response(error_message(20, e.message), e.status) | |
end | |
rescue_from :all do |e| | |
if Rails.env.development? | |
raise e | |
else | |
rack_response(error_message(500, 'internal server error'), 500) | |
end | |
end | |
# mounts goes here | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment