Permalink
Browse files

Trap all JSON decoding errors; raise MultiJson::EncodeError

Closes #3
  • Loading branch information...
sferik committed Oct 19, 2010
1 parent 10c365f commit dea9a1aef6dd1212aa1e5a37ab1669f9b045b732
Showing with 13 additions and 2 deletions.
  1. +6 −1 lib/multi_json.rb
  2. +7 −1 spec/multi_json_spec.rb
View
@@ -1,4 +1,5 @@
module MultiJson
+ class DecodeError < StandardError; end
module_function
# Get the current engine class.
@@ -59,7 +60,11 @@ def engine=(new_engine)
#
# <tt>:symbolize_keys</tt> :: If true, will use symbols instead of strings for the keys.
def decode(string, options = {})
- engine.decode(string, options)
+ begin
+ engine.decode(string, options)
+ rescue StandardError => exception
+ raise DecodeError, exception.inspect
+ end
end
# Encodes a Ruby object as JSON.
View
@@ -50,10 +50,16 @@ def self.encode(string)
end
describe '.decode' do
- it 'should properly decode some json' do
+ it 'should properly decode valid JSON' do
MultiJson.decode('{"abc":"def"}').should == {'abc' => 'def'}
end
+ it 'should raise MultiJson::DecodeError on invalid JSON' do
+ lambda do
+ MultiJson.decode('{"abc"}')
+ end.should raise_error(MultiJson::DecodeError)
+ end
+
it 'should allow for symbolization of keys' do
MultiJson.decode('{"abc":{"def":"hgi"}}', :symbolize_keys => true).should == {:abc => {:def => 'hgi'}}
end

0 comments on commit dea9a1a

Please sign in to comment.