Просмотр исходного кода

Fix error response when constraint validation fails

Loïc Hoguin 7 лет назад
Родитель
Сommit
fda2d150db
2 измененных файлов с 20 добавлено и 8 удалено
  1. 15 8
      src/cowboy_req.erl
  2. 5 0
      test/req_SUITE.erl

+ 15 - 8
src/cowboy_req.erl

@@ -194,7 +194,13 @@ parse_qs(#{qs := Qs}) ->
 
 -spec match_qs(cowboy:fields(), req()) -> map().
 match_qs(Fields, Req) ->
-	filter(Fields, kvlist_to_map(Fields, parse_qs(Req))).
+	case filter(Fields, kvlist_to_map(Fields, parse_qs(Req))) of
+		{ok, Map} ->
+			Map;
+		{error, Errors} ->
+			exit({request_error, {match_qs, Errors},
+				'Query string validation constraints failed for the reasons provided.'})
+	end.
 
 -spec uri(req()) -> iodata().
 uri(Req) ->
@@ -407,7 +413,13 @@ parse_cookies(Req) ->
 
 -spec match_cookies(cowboy:fields(), req()) -> map().
 match_cookies(Fields, Req) ->
-	filter(Fields, kvlist_to_map(Fields, parse_cookies(Req))).
+	case filter(Fields, kvlist_to_map(Fields, parse_cookies(Req))) of
+		{ok, Map} ->
+			Map;
+		{error, Errors} ->
+			exit({request_error, {match_cookies, Errors},
+				'Cookie validation constraints failed for the reasons provided.'})
+	end.
 
 %% Request body.
 
@@ -803,12 +815,7 @@ kvlist_to_map(Keys, [{Key, Value}|Tail], Map) ->
 	end.
 
 filter(Fields, Map0) ->
-	case filter(Fields, Map0, #{}) of
-		{ok, Map} ->
-			Map;
-		{error, Errors} ->
-			exit({validation_failed, Errors})
-	end.
+	filter(Fields, Map0, #{}).
 
 %% Loop through fields, if value is missing and no default,
 %% record the error; else if value is missing and has a

+ 5 - 0
test/req_SUITE.erl

@@ -171,6 +171,9 @@ match_cookies(Config) ->
 	<<"#{c => <<\"d\">>}">> = do_get_body("/match/cookies/c", [{<<"cookie">>, "a=b; c=d"}], Config),
 	<<"#{a => <<\"b\">>,c => <<\"d\">>}">> = do_get_body("/match/cookies/a/c",
 		[{<<"cookie">>, "a=b; c=d"}], Config),
+	%% Ensure match errors result in a 400 response.
+	{400, _, _} = do_get("/match/cookies/a/c",
+		[{<<"cookie">>, "a=b"}], Config),
 	%% This function is tested more extensively through unit tests.
 	ok.
 
@@ -183,6 +186,8 @@ match_qs(Config) ->
 	<<"#{a => <<\"b\">>,c => <<\"d\">>}">> = do_get_body("/match/qs/a/c?a=b&c=d", Config),
 	<<"#{a => <<\"b\">>,c => true}">> = do_get_body("/match/qs/a/c?a=b&c", Config),
 	<<"#{a => true,c => <<\"d\">>}">> = do_get_body("/match/qs/a/c?a&c=d", Config),
+	%% Ensure match errors result in a 400 response.
+	{400, _, _} = do_get("/match/qs/a/c?a=b", [], Config),
 	%% This function is tested more extensively through unit tests.
 	ok.