class Api::ApiController < ActionController::Base skip_before_action :verify_authenticity_token include Knock::Authenticable include Pundit rescue_from Exception, :with => :return_error before_action :authenticate_user before_action do Current.user = current_user if current_user.present? end def pundit_user UserContext.new(Current.user, Current.account) end # Catch exception and return JSON-formatted error def return_error(exception) raise exception if Rails.env.test? Raven.capture_exception(exception) logger.error "==Handled======" logger.error exception.message logger.error exception.backtrace.join("\n") logger.error "==Handled=======" case exception.class when ActiveRecord::RecordNotFound @status = 404 @message = 'Record not found' when ActiveRecord::RecordInvalid @status = 422 @message = 'Record invalid' when ArgumentError @status = 400 @message = 'Argument Error' else @status = 500 @message = 'Internal Error' end # for some reason render json_errors is not working # simulating JSON API support render json: { errors: [{ status: @status.to_s, title: @message }] } end end