Skip to content

Commit 19ddafd

Browse files
committed
Set data context to DecodeError exception #21
Sometimes indirect clients of MultiJson have no easy way to determine the data attempting to be parsed into JSON, therefore a data attribute is added to MultiJson::DecodeError class and attribute is set when raising the exception.
1 parent b1cd6d9 commit 19ddafd

2 files changed

Lines changed: 20 additions & 2 deletions

File tree

lib/multi_json.rb

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,14 @@
11
module MultiJson
2-
class DecodeError < StandardError; end
2+
class DecodeError < StandardError
3+
attr_reader :data
4+
def initialize(message, backtrace, data)
5+
super(message)
6+
self.set_backtrace(backtrace)
7+
self.data= data
8+
end
9+
private
10+
attr_writer :data
11+
end
312
module_function
413

514
@engine = nil
@@ -64,7 +73,7 @@ def engine=(new_engine)
6473
def decode(string, options = {})
6574
engine.decode(string, options)
6675
rescue engine::ParseError => exception
67-
raise DecodeError, exception.message, exception.backtrace
76+
raise DecodeError.new(exception.message, exception.backtrace, string)
6877
end
6978

7079
# Encodes a Ruby object as JSON.

spec/multi_json_spec.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,15 @@
100100
end.should raise_error(MultiJson::DecodeError)
101101
end
102102

103+
it 'raises MultiJson::DecodeError with data on invalid JSON' do
104+
data = '{crapper}'
105+
begin
106+
MultiJson.decode(data)
107+
rescue MultiJson::DecodeError => de
108+
de.data.should == data
109+
end
110+
end
111+
103112
it 'stringifys symbol keys when encoding' do
104113
encoded_json = MultiJson.encode(:a => 1, :b => {:c => 2})
105114
MultiJson.decode(encoded_json).should == { "a" => 1, "b" => { "c" => 2 } }

0 commit comments

Comments
 (0)