From 5a0759a3d91a0b1226b539f9962e25e76ad20128 Mon Sep 17 00:00:00 2001 From: Frank Rousseau Date: Sun, 21 May 2017 00:27:20 +0200 Subject: [PATCH] Add exception handlers in base API controller * For record not found returns a 404 response * For wrong parameters returns a 400 response * For other exceptions returns a 500 response --- app/controllers/api/v0/base_controller.rb | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/app/controllers/api/v0/base_controller.rb b/app/controllers/api/v0/base_controller.rb index 77805a591..0ff5b2219 100644 --- a/app/controllers/api/v0/base_controller.rb +++ b/app/controllers/api/v0/base_controller.rb @@ -7,6 +7,26 @@ module Api protected + rescue_from Exception do |e| + logger.error e.message + render json: {error: e.message}, status: 500 + end + + rescue_from ActiveRecord::RecordNotFound do + render json: {error: I18n.t("api.error.not_found")}, status: 404 + end + + rescue_from ActiveRecord::RecordInvalid do |e| + render json: {error: e.to_s}, status: 400 + end + + rescue_from ActionController::ParameterMissing do |e| + render json: { + error: I18n.t("api.error.wrong_parameters"), + message: e.message + }, status: 400 + end + def current_user current_token ? current_token.authorization.user : nil end