Skip to content

Commit

Permalink
Passing current user to error handler on argument error
Browse files Browse the repository at this point in the history
  • Loading branch information
btolarz committed Feb 16, 2021
1 parent 81a55c3 commit fa7f883
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 6 deletions.
2 changes: 1 addition & 1 deletion api/app/controllers/spree/api/v2/base_controller.rb
Expand Up @@ -101,7 +101,7 @@ def gateway_error(exception)
end

def error_during_processing(exception)
result = error_handler.call(exception: exception)
result = error_handler.call(exception: exception, opts: { user: spree_current_user })

render_error_payload(result.value[:message], 400)
end
Expand Down
9 changes: 5 additions & 4 deletions api/app/services/spree/api/error_handler.rb
Expand Up @@ -3,15 +3,15 @@ module Api
class ErrorHandler
prepend ::Spree::ServiceModule::Base

def call(exception:)
def call(exception:, opts: {})
run :format_message
run :log_error
run :report_error
end

protected

def format_message(exception:)
def format_message(exception:, opts:)
message = if exception.respond_to?(:original_message)
exception.original_message
else
Expand All @@ -21,14 +21,15 @@ def format_message(exception:)
success(exception: exception, message: message)
end

def log_error(exception:, message:)
def log_error(exception:, message:, opts:)
Rails.logger.error message
Rails.logger.error "User ID: #{opts[:user]&.id}" if opts[:user]
Rails.logger.error exception.backtrace.join("\n")

success(exception: exception, message: message)
end

def report_error(exception:, message:)
def report_error(exception:, message:, opts:)
# overwrite this method in your application to support different error handlers
# eg. Sentry, Rollbar, etc

Expand Down
7 changes: 6 additions & 1 deletion api/spec/controllers/spree/api/v2/base_controller_spec.rb
Expand Up @@ -103,14 +103,19 @@ def index
end
end

let!(:user) { create :user }
let(:exception) { ArgumentError.new('foo') }
let(:result_class) { Struct.new(:value) }
let(:result) { result_class.new({message: 'foo'}) }

it 'handles ArgumentError exceptions' do
expect(subject).to receive(:index).and_raise(exception)
expect(subject).to receive(:spree_current_user).and_return(user)
expect_next_instance_of(::Spree::Api::ErrorHandler) do |instance|
expect(instance).to receive(:call).with(exception: exception).and_return(result)
expect(instance).to receive(:call).with(
exception: exception,
opts: { user: user }
).and_return(result)
end
get :index, params: { token: 'exception-message' }
expect(json_response).to eql('error' => 'foo')
Expand Down

0 comments on commit fa7f883

Please sign in to comment.