Erlang JSON decode with error context
Erlang
-module(json_errors).
-export([decode/1]).
%% Requires OTP 27+ for the stdlib json module.
decode(Bin) when is_binary(Bin) ->
try json:decode(Bin) of
Json -> {ok, Json}
catch
error:Reason -> {error, {invalid_json, Reason, snippet(Bin)}}
end;
decode(Other) ->
{error, {not_binary, Other}}.
snippet(Bin) when byte_size(Bin) =< 60 -> Bin;
snippet(Bin) ->
<<Prefix:60/binary, _/binary>> = Bin,
<<Prefix/binary, "...">>.