From eaeedfd6c133fa1c7008a344c96451d3117339d0 Mon Sep 17 00:00:00 2001 From: Stephan Renatus Date: Tue, 20 Jun 2017 12:40:06 +0200 Subject: [PATCH] Catch and re-throw big exponent exceptions ``` $ rebar3 shell ===> Verifying dependencies... ===> Compiling jiffy Erlang/OTP 18 [erts-7.3] [source] [64-bit] [smp:8:8] [async-threads:0] [hipe] [kernel-poll:false] Eshell V7.3 (abort with ^G) 1> jiffy:decode(<<"[1e310]">>). ** exception error: an error occurred when evaluating an arithmetic expression in function math:pow/2 called as math:pow(10,310) in call from jiffy:finish_decode/1 (jiffy/_build/default/lib/jiffy/src/jiffy.erl, line 118) in call from jiffy:finish_decode_arr/2 (jiffy/_build/default/lib/jiffy/src/jiffy.erl, line 149) 2> jiffy:decode(<<"[0.2e310]">>). ** exception error: bad argument in function list_to_float/1 called as list_to_float("0.2e310") in call from jiffy:finish_decode/1 (jiffy/_build/default/lib/jiffy/src/jiffy.erl, line 120) in call from jiffy:finish_decode_arr/2 (jiffy/_build/default/lib/jiffy/src/jiffy.erl, line 149) 3> ``` That `310` could depend on my machine, since `math:pow/2` says it's a limitation coming from libc. With this change, this still throws an exception, but it doesn't come from math or erlang, but jiffy: ``` 1> jiffy:decode(<<"[1e310]">>). ** exception throw: {error,{range,310}} in function jiffy:finish_decode/1 (jiffy/_build/default/lib/jiffy/src/jiffy.erl, line 121) in call from jiffy:finish_decode_arr/2 (jiffy/_build/default/lib/jiffy/src/jiffy.erl, line 157) 2> ``` Signed-off-by: Stephan Renatus --- src/jiffy.erl | 12 ++++++++++-- test/jiffy_03_number_tests.erl | 2 ++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/jiffy.erl b/src/jiffy.erl index 08fa3c0..8b9432f 100644 --- a/src/jiffy.erl +++ b/src/jiffy.erl @@ -115,9 +115,17 @@ finish_decode({bignum_e, Value}) -> {E, []} = string:to_integer(ExpStr), {I, E} end, - IVal * math:pow(10, EVal); + try + IVal * math:pow(10, EVal) + catch + error:badarith -> throw({error, {range, EVal}}) + end; finish_decode({bigdbl, Value}) -> - list_to_float(binary_to_list(Value)); + try + list_to_float(binary_to_list(Value)) + catch + error:badarg -> throw({error, {range, Value}}) + end; finish_decode({Pairs}) when is_list(Pairs) -> finish_decode_obj(Pairs, []); finish_decode(Vals) when is_list(Vals) -> diff --git a/test/jiffy_03_number_tests.erl b/test/jiffy_03_number_tests.erl index ac7b95f..f30b52e 100644 --- a/test/jiffy_03_number_tests.erl +++ b/test/jiffy_03_number_tests.erl @@ -97,6 +97,8 @@ cases(error) -> <<"1E">>, <<"1-E2">>, <<"2E +3">>, + <<"1E3000">>, + <<"0.1E30000">>, <<"1EA">> ];