Skip to content

Commit dea9a1a

Browse files
committed
Trap all JSON decoding errors; raise MultiJson::EncodeError
Closes #3
1 parent 10c365f commit dea9a1a

2 files changed

Lines changed: 13 additions & 2 deletions

File tree

lib/multi_json.rb

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
module MultiJson
2+
class DecodeError < StandardError; end
23
module_function
34

45
# Get the current engine class.
@@ -59,7 +60,11 @@ def engine=(new_engine)
5960
#
6061
# <tt>:symbolize_keys</tt> :: If true, will use symbols instead of strings for the keys.
6162
def decode(string, options = {})
62-
engine.decode(string, options)
63+
begin
64+
engine.decode(string, options)
65+
rescue StandardError => exception
66+
raise DecodeError, exception.inspect
67+
end
6368
end
6469

6570
# Encodes a Ruby object as JSON.

spec/multi_json_spec.rb

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,16 @@ def self.encode(string)
5050
end
5151

5252
describe '.decode' do
53-
it 'should properly decode some json' do
53+
it 'should properly decode valid JSON' do
5454
MultiJson.decode('{"abc":"def"}').should == {'abc' => 'def'}
5555
end
5656

57+
it 'should raise MultiJson::DecodeError on invalid JSON' do
58+
lambda do
59+
MultiJson.decode('{"abc"}')
60+
end.should raise_error(MultiJson::DecodeError)
61+
end
62+
5763
it 'should allow for symbolization of keys' do
5864
MultiJson.decode('{"abc":{"def":"hgi"}}', :symbolize_keys => true).should == {:abc => {:def => 'hgi'}}
5965
end

0 commit comments

Comments
 (0)