Skip to content

Commit 68b75ff

Browse files
authored
fix(router): Fixed double-encoding the malformed-body 400 response (#108)
1 parent 70f1a1b commit 68b75ff

2 files changed

Lines changed: 51 additions & 8 deletions

File tree

‎src/erf_router.erl‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -129,13 +129,11 @@ handle(Name, RawRequest) ->
129129
end;
130130
{error, _Reason} ->
131131
ContentTypeHeader = string:casefold(<<"content-type">>),
132-
ErrorBody = iolist_to_binary(
133-
json:encode(#{
134-
<<"title">> => <<"Bad Request">>,
135-
<<"status">> => 400,
136-
<<"detail">> => <<"Failed to read request">>
137-
})
138-
),
132+
ErrorBody = #{
133+
<<"title">> => <<"Bad Request">>,
134+
<<"status">> => 400,
135+
<<"detail">> => <<"Failed to read request">>
136+
},
139137
ResponseError = {400, [{ContentTypeHeader, <<"application/json">>}], ErrorBody},
140138
{ResponseError, RawRequest}
141139
end,

‎test/erf_SUITE.erl‎

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,8 @@ all() ->
3636
stream_producer_crash,
3737
stream_non_200_status,
3838
callback_crash,
39-
json_content_type
39+
json_content_type,
40+
malformed_body
4041
].
4142

4243
%%%-----------------------------------------------------------------------------
@@ -952,6 +953,50 @@ json_content_type(_Conf) ->
952953

953954
ok.
954955

956+
malformed_body(_Conf) ->
957+
meck:new([erf_callback], [non_strict, no_link]),
958+
959+
meck:expect(
960+
erf_callback,
961+
create_foo,
962+
fun(_Request) ->
963+
{201, [], <<"bar">>}
964+
end
965+
),
966+
967+
{ok, _Pid} = erf:start_link(#{
968+
spec_path => filename:join(
969+
[code:lib_dir(erf), "test", <<"fixtures/with_refs_oas_3_0_spec.json">>]
970+
),
971+
callback => erf_callback,
972+
port => 8789,
973+
name => erf_server
974+
}),
975+
976+
{ok, {{"HTTP/1.1", 400, "Bad Request"}, Headers, Body}} =
977+
httpc:request(
978+
post,
979+
{"http://localhost:8789/1/foo", [], "application/json", <<"{oops">>},
980+
[],
981+
[{body_format, binary}]
982+
),
983+
984+
?assertEqual("application/json", proplists:get_value("content-type", Headers)),
985+
?assertEqual(
986+
#{
987+
<<"title">> => <<"Bad Request">>,
988+
<<"status">> => 400,
989+
<<"detail">> => <<"Failed to read request">>
990+
},
991+
json:decode(Body)
992+
),
993+
994+
ok = erf:stop(erf_server),
995+
996+
meck:unload(erf_callback),
997+
998+
ok.
999+
9551000
%%%-----------------------------------------------------------------------------
9561001
%%% INTERNAL HELPERS
9571002
%%%-----------------------------------------------------------------------------

0 commit comments

Comments
 (0)