Skip to content

Commit aa90b0a

Browse files
authored
Merge pull request #316 from 1debit/customize_errors
Allow custom error messages
2 parents 90fb6ef + 524f968 commit aa90b0a

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

lib/json_api_client/resource.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -584,10 +584,14 @@ def relationships_for_serialization
584584
relationships.as_json_api
585585
end
586586

587+
def error_message_for(error)
588+
error.error_msg
589+
end
590+
587591
def fill_errors
588592
last_result_set.errors.each do |error|
589593
key = self.class.key_formatter.unformat(error.error_key)
590-
errors.add(key, error.error_msg)
594+
errors.add(key, error_message_for(error))
591595
end
592596
end
593597
end

test/unit/error_collector_test.rb

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,48 @@ def test_can_handle_parameter_error
215215
assert_equal "include", error.source_parameter
216216
end
217217

218+
describe 'custom error_msg_key' do
219+
class CustomErrorArticle < TestResource
220+
def error_message_for(error)
221+
error.detail
222+
end
223+
end
224+
225+
def test_can_handle_custom_parameter_error
226+
stub_request(:post, "http://example.com/custom_error_articles")
227+
.with(headers: {content_type: "application/vnd.api+json", accept: "application/vnd.api+json"}, body: {
228+
data: {
229+
type: "custom_error_articles",
230+
attributes: {
231+
title: "Rails is Omakase",
232+
email_address: "bar"
233+
}
234+
}
235+
}.to_json)
236+
.to_return(headers: {content_type: "application/vnd.api+json"}, body: {
237+
errors: [
238+
{
239+
id: "1234-abcd",
240+
status: "400",
241+
code: "1337",
242+
title: "bar is required",
243+
detail: "bar include is required for creation",
244+
source: {
245+
parameter: "include"
246+
}
247+
}
248+
]
249+
}.to_json)
250+
251+
article = CustomErrorArticle.create({
252+
title: "Rails is Omakase",
253+
email_address: "bar"
254+
})
255+
256+
assert_equal ["bar include is required for creation"], article.errors[:base]
257+
end
258+
end
259+
218260
def test_can_handle_explicit_null_error_values
219261
stub_request(:post, "http://example.com/articles")
220262
.with(headers: {content_type: "application/vnd.api+json", accept: "application/vnd.api+json"}, body: {

0 commit comments

Comments
 (0)