From e1020f9f5c757b7cd0d7d4e875e33c12abb33183 Mon Sep 17 00:00:00 2001 From: Robert Speicher Date: Mon, 25 Nov 2019 12:14:13 -0600 Subject: [PATCH] Forward missing messages on Error to the parsed response An error response may contain useful additional context, and this allows users to access that context on the exception class. For example, the cherry-pick API now includes an `error_code` field to indicate why the cherry-pick failed, which can now be accessed via `Error#error_code`. --- lib/gitlab/error.rb | 12 ++++++++++++ spec/gitlab/error_spec.rb | 16 ++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/lib/gitlab/error.rb b/lib/gitlab/error.rb index df463d6c8..70d4e4479 100644 --- a/lib/gitlab/error.rb +++ b/lib/gitlab/error.rb @@ -78,6 +78,18 @@ def handle_message(message) message end end + + def method_missing(method, *args, &block) + if @response.parsed_response.key?(method) + @response.parsed_response[method] + else + super + end + end + + def respond_to_missing?(method, include_private = false) + super || @response.parsed_response.key?(method, include_private) + end end # Raised when API endpoint returns the HTTP status code 400. diff --git a/spec/gitlab/error_spec.rb b/spec/gitlab/error_spec.rb index f5f1538a9..c0df30af2 100644 --- a/spec/gitlab/error_spec.rb +++ b/spec/gitlab/error_spec.rb @@ -51,4 +51,20 @@ response_double = double('response', body: 'Retry later', to_s: 'Retry text', parsed_response: { message: 'Retry hash' }, code: 429, options: {}, headers: headers, request: @request_double) expect(described_class.new(response_double).send(:build_error_message)).to match(/Retry hash/) end + + it 'passes missing messages to the parsed response' do + response_hash = { message: 'Failed to cherry-pick', error_code: 'empty' } + response_double = double( + 'response', + body: JSON.dump(response_hash), + parsed_response: response_hash, + code: 400, + headers: { 'content-type' => 'application/json' }, + request: @request_double + ) + + error = described_class.new(response_double) + + expect(error.error_code).to eq(response_hash[:error_code]) + end end