vereto-api/app/controllers/concerns/exception_handler.rb

34 lines
1.1 KiB
Ruby
Raw Normal View History

2018-02-16 15:02:03 +00:00
# I made this file lel
2018-02-16 11:52:56 +00:00
module ExceptionHandler
extend ActiveSupport::Concern
2018-02-16 15:02:03 +00:00
# Define custom error subclasses - rescue catches `StandardErrors`
class AuthenticationError < StandardError; end
class MissingToken < StandardError; end
class InvalidToken < StandardError; end
2018-02-16 11:52:56 +00:00
included do
2018-02-16 15:02:03 +00:00
# Define custom handlers
rescue_from ActiveRecord::RecordInvalid, with: :four_twenty_two
rescue_from ExceptionHandler::AuthenticationError, with: :unauthorized_request
rescue_from ExceptionHandler::MissingToken, with: :four_twenty_two
rescue_from ExceptionHandler::InvalidToken, with: :four_twenty_two
2018-02-16 11:52:56 +00:00
rescue_from ActiveRecord::RecordNotFound do |e|
json_response({ message: e.message}, :not_found)
end
2018-02-16 15:02:03 +00:00
end
2018-02-16 11:52:56 +00:00
2018-02-16 15:02:03 +00:00
private
# JSON Resoinse with message; Status code 422 - unprocessable entity
def four_twenty_two(e)
json_response({ message: e.message}, :unprocessable_entity)
end
# JSON Response with message; Status code 401 - Unauthorized
def unauthorized_request(e)
json_response({ message: e.message }, :unauthorized)
2018-02-16 11:52:56 +00:00
end
end