ソースを参照

Merge pull request #10911 from kjellwinblad/kjell/bridge/atom_length_too_long/EMQX-9609

fix: friendly error message when creating bridges with too long names
Kjell Winblad 2 年 前
コミット
273dedf7a6

+ 11 - 0
apps/emqx/src/emqx_config_handler.erl

@@ -457,6 +457,17 @@ bin_path(ConfKeyPath) -> [bin(Key) || Key <- ConfKeyPath].
 bin(A) when is_atom(A) -> atom_to_binary(A, utf8);
 bin(B) when is_binary(B) -> B.
 
+atom(Bin) when is_binary(Bin), size(Bin) > 255 ->
+    erlang:throw(
+        iolist_to_binary(
+            io_lib:format(
+                "Name is is too long."
+                " Please provide a shorter name (<= 255 bytes)."
+                " The name that is too long: \"~s\"",
+                [Bin]
+            )
+        )
+    );
 atom(Bin) when is_binary(Bin) ->
     binary_to_atom(Bin, utf8);
 atom(Str) when is_list(Str) ->

+ 1 - 1
apps/emqx_bridge/src/emqx_bridge_api.erl

@@ -602,7 +602,7 @@ create_or_update_bridge(BridgeType, BridgeName, Conf, HttpStatusCode) ->
     case emqx_bridge:create(BridgeType, BridgeName, Conf) of
         {ok, _} ->
             lookup_from_all_nodes(BridgeType, BridgeName, HttpStatusCode);
-        {error, #{kind := validation_error} = Reason} ->
+        {error, Reason} when is_map(Reason) ->
             ?BAD_REQUEST(map_to_json(Reason))
     end.
 

+ 20 - 0
apps/emqx_bridge/test/emqx_bridge_api_SUITE.erl

@@ -421,6 +421,26 @@ t_http_crud_apis(Config) ->
     ),
 
     %% Test bad updates
+    %% ================
+
+    %% Add bridge with a name that is too long
+    %% We only support bridge names up to 255 characters
+    LongName = list_to_binary(lists:duplicate(256, $a)),
+    NameTooLongRequestResult = request_json(
+        post,
+        uri(["bridges"]),
+        ?HTTP_BRIDGE(URL1, LongName),
+        Config
+    ),
+    ?assertMatch(
+        {ok, 400, _},
+        NameTooLongRequestResult
+    ),
+    {ok, 400, #{<<"message">> := NameTooLongMessage}} = NameTooLongRequestResult,
+    %% Use regex to check that the message contains the name
+    Match = re:run(NameTooLongMessage, LongName),
+    ?assertMatch({match, _}, Match),
+    %% Add bridge without the URL field
     {ok, 400, PutFail1} = request_json(
         put,
         uri(["bridges", BridgeID]),

+ 1 - 0
changes/ce/fix-10911.en.md

@@ -0,0 +1 @@
+The error message and log entry that appear when one tries to create a bridge with a name the exceeds 255 bytes is now easier to understand.