Able to encode but decode crash on simple record.
Closed this issue · 2 comments
All the fields are encodes as binary string.
-------------------------chat_message.hrl-----------------------------------------------
-ifndef(CHAT_MESSAGE_HRL).
-define(CHAT_MESSAGE_HRL, true).
-record(chat_message, {
from ::binary(),
to ::binary(),
brandId ::binary(),
type ::binary(),
format ::binary(),
subject ::binary(),
body ::binary(),
thread ::binary(),
time_stamp ::binary()}).
-export_records([chat_message]).
-endif.
-module(chat_message_model).
-include_lib("jsonrec.hrl").
-include_lib("chat_message.hrl").
-export([encode/1, decode/1]).
encode(#chat_message{} = Rec) ->
?encode_gen(#chat_message{}, Rec).
decode(Payload) ->
?decode_gen(#chat_message{}, Payload).
Code to encode and decode:
Payload0 = chat_message_model:encode(Payload),
chat_message_model:decode(Payload0),
After encode, here is the data:
[<<"{">>,[""from"",<<":">>,[34,<<"270297119">>,34],<<",">>,""to"",<<":">>,[34,<<"116688729">>,34],<<",">>,""brandId"",<<":">>,[34,<<"1003">>,34],<<",">>,""type"",<<":">>,[34,<<"chat">>,34],<<",">>,""format"",<<":">>,[34,<<"chat">>,34],<<",">>,""subject"",<<":">>,[34,<<"1386199916344270297119116688729116688729270297119">>,34],<<",">>,""body"",<<":">>,[34,[<<"Consumer Service Test Msg-12">>,<<"/">>,<<" 6">>,<<"/">>,<<"0043 19:49:28 From Server: spark_rabbit_consumer@192.168.4.124">>],34],<<",">>,""thread"",<<":">>,[34,<<"1386199916344270297119116688729">>,34],<<",">>,""time_stamp"",<<":">>,[34,[<<"12">>,<<"/">>,<<" 6">>,<<"/">>,<<"0043 19:49:28">>],34]],<<"}">>]
Then decode says:
{error,{expected,<<"{">>,at,[<<"{">>,[""from"",<<":">>,[34,<<"270297119">>,34],<<",">>,""to"",<<":">>,[34,<<"116688729">>,34],<<",">>,""brandId"",<<":">>,[34,<<"1003">>,34],<<",">>,""type"",<<":">>,[34,<<"chat">>,34],<<",">>,""format"",<<":">>,[34,<<"chat">>,34],<<",">>,""subject"",<<":">>,[34,<<"1386199916344270297119116688729116688729270297119">>,34],<<",">>,""body"",<<":">>,[34,[<<"Consumer Service Test Msg-12">>,<<"/">>,<<" 6">>,<<"/">>,<<"0043 19:49:28 From Server: spark_rabbit_consumer@192.168.4.124">>],34],<<",">>,""thread"",<<":">>,[34,<<"1386199916344270297119116688729">>,34],<<",">>,""time_stamp"",<<":">>,[34,[<<"12">>,<<"/">>,<<" 6">>,<<"/">>,<<"0043 19:49:28">>],34]],<<"}">>]}}
I agree, the error is cryptic, but the actual problem is that encode/1
returns iolist()
while decode/1
expects binary()
. To make your example work just convert the result of encode
to binary()
using erlang:iolist_to_binary/1
(or even erlang:list_to_binary/1
) before passing to to decode/1
:
Payload0 = chat_message_model:encode(Payload),
chat_message_model:decode(list_to_binary(Payload0)).
thanks. Just a note, would you mind highlight the hint in the error that can help me identify this? I would like to know where to look next time, so not to repeat the same mistake before going into the library source code.