Skip to content

Commit

Permalink
[Fix] Handle JSON::Parser Error
Browse files Browse the repository at this point in the history
Signed-off-by: Michael Marusyk <[email protected]>
  • Loading branch information
mmarusyk committed Oct 16, 2024
1 parent e6dff80 commit 81bc237
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 6 deletions.
4 changes: 3 additions & 1 deletion lib/easyship/handlers/response_body_handler.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ class ResponseBodyHandler
def self.handle_response(response)
body = response.body

JSON.parse(body, symbolize_names: true) unless body.nil? || body.empty?
JSON.parse(body, symbolize_names: true)
rescue JSON::ParserError
nil
end
end
end
Expand Down
9 changes: 6 additions & 3 deletions lib/easyship/middleware/error_handler_middleware.rb
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
# frozen_string_literal: true

require_relative '../error'

module Easyship
module Middleware
# Response middleware that raises an error based on the response status code
class ErrorHandlerMiddleware < Faraday::Middleware
def on_complete(env)
status_code = env[:status].to_i
body = JSON.parse(env[:body], symbolize_names: true) if json?(env[:body])
body = response_body(env[:body])

handle_status_code(status_code, body)
end
Expand Down Expand Up @@ -54,8 +55,10 @@ def format_by_default(body)
{ details: body, message: 'Something went wrong.' }
end

def json?(body)
!body.nil? && body.is_a?(String)
def response_body(body)
JSON.parse(body, symbolize_names: true)
rescue JSON::ParserError
nil
end
end
end
Expand Down
45 changes: 45 additions & 0 deletions spec/cassettes/server_error.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 8 additions & 2 deletions spec/easyship/client_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@
end

context 'when invalid api_key' do
let(:path) { '/2023-01/account' }

it 'raises an InvalidTokenError' do
VCR.use_cassette('invalid_token') do
expect { client.get(path) }.to raise_error(Easyship::Errors::InvalidTokenError)
Expand All @@ -33,6 +31,14 @@
end
end
end

context 'when internal server error' do
it 'raises an ServerError' do
VCR.use_cassette('server_error') do
expect { client.get(path) }.to raise_error(Easyship::Errors::ServerError)
end
end
end
end

describe '#post' do
Expand Down

0 comments on commit 81bc237

Please sign in to comment.