Improve try catch syntax (#2263)

* Replace case catch.. with try ... catch
Prior to this change, case catch ... would cost a lot of performance
because it would retrieve the whole stacktrace. However, try...catch
will not retrieve the whole stacktrace. So try...catch syntax is better.
This commit is contained in:
Gilbert 2019-02-28 09:54:28 +08:00 committed by turtleDeng
parent a0fd9e63e0
commit c3e6f3c3b2
8 changed files with 72 additions and 54 deletions

View File

@ -39,4 +39,3 @@
begin begin
(logger:log(Level,#{},#{report_cb => fun(_) -> {(Format), (Args)} end})) (logger:log(Level,#{},#{report_cb => fun(_) -> {(Format), (Args)} end}))
end). end).

View File

@ -17,6 +17,7 @@
-behaviour(gen_server). -behaviour(gen_server).
-include("emqx.hrl"). -include("emqx.hrl").
-include("logger.hrl").
-export([start_link/0]). -export([start_link/0]).
-export([authenticate/2]). -export([authenticate/2]).
@ -68,7 +69,7 @@ authenticate(Credentials, _Password, []) ->
end; end;
authenticate(Credentials, Password, [{Mod, State, _Seq} | Mods]) -> authenticate(Credentials, Password, [{Mod, State, _Seq} | Mods]) ->
case catch Mod:check(Credentials, Password, State) of try Mod:check(Credentials, Password, State) of
ok -> ok; ok -> ok;
{ok, IsSuper} when is_boolean(IsSuper) -> {ok, IsSuper} when is_boolean(IsSuper) ->
{ok, #{is_superuser => IsSuper}}; {ok, #{is_superuser => IsSuper}};
@ -79,9 +80,11 @@ authenticate(Credentials, Password, [{Mod, State, _Seq} | Mods]) ->
ignore -> ignore ->
authenticate(Credentials, Password, Mods); authenticate(Credentials, Password, Mods);
{error, Reason} -> {error, Reason} ->
{error, Reason}; {error, Reason}
{'EXIT', Error} -> catch
{error, Error} error:Reason:StackTrace ->
?LOG(error, "Authenticate failed. StackTrace: ~p", [StackTrace]),
{error, Reason}
end. end.
%% @doc Check ACL %% @doc Check ACL
@ -206,4 +209,3 @@ code_change(_OldVsn, State, _Extra) ->
reply(Reply, State) -> reply(Reply, State) ->
{reply, Reply, State}. {reply, Reply, State}.

View File

@ -17,6 +17,7 @@
-behaviour(emqx_acl_mod). -behaviour(emqx_acl_mod).
-include("emqx.hrl"). -include("emqx.hrl").
-include("logger.hrl").
-export([all_rules/0]). -export([all_rules/0]).
@ -63,7 +64,7 @@ load_rules_from_file(AclFile) ->
emqx_logger:error("[ACL_INTERNAL] Failed to read ~s: ~p", [AclFile, Reason]), emqx_logger:error("[ACL_INTERNAL] Failed to read ~s: ~p", [AclFile, Reason]),
{error, Reason} {error, Reason}
end. end.
filter(_PubSub, {allow, all}) -> filter(_PubSub, {allow, all}) ->
true; true;
filter(_PubSub, {deny, all}) -> filter(_PubSub, {deny, all}) ->
@ -105,17 +106,18 @@ match(Credentials, Topic, [Rule|Rules]) ->
-spec(reload_acl(state()) -> ok | {error, term()}). -spec(reload_acl(state()) -> ok | {error, term()}).
reload_acl(#{acl_file := AclFile}) -> reload_acl(#{acl_file := AclFile}) ->
case catch load_rules_from_file(AclFile) of try load_rules_from_file(AclFile) of
ok -> ok ->
emqx_logger:info("Reload acl_file ~s successfully", [AclFile]), emqx_logger:info("Reload acl_file ~s successfully", [AclFile]),
ok; ok;
{error, Error} -> {error, Error} ->
{error, Error};
{'EXIT', Error} ->
{error, Error} {error, Error}
catch
error:Reason:StackTrace ->
?LOG(error, "Reload acl failed. StackTrace: ~p", [StackTrace]),
{error, Reason}
end. end.
-spec(description() -> string()). -spec(description() -> string()).
description() -> description() ->
"Internal ACL with etc/acl.conf". "Internal ACL with etc/acl.conf".

View File

@ -60,19 +60,21 @@ show_forwards(Name) ->
-spec(add_forward(atom(), binary()) -> ok | {error, already_exists | validate_fail}). -spec(add_forward(atom(), binary()) -> ok | {error, already_exists | validate_fail}).
add_forward(Name, Topic) -> add_forward(Name, Topic) ->
case catch emqx_topic:validate({filter, Topic}) of try emqx_topic:validate({filter, Topic}) of
true -> true ->
gen_server:call(name(Name), {add_forward, Topic}); gen_server:call(name(Name), {add_forward, Topic})
{'EXIT', _Reason} -> catch
_Error:_Reason ->
{error, validate_fail} {error, validate_fail}
end. end.
-spec(del_forward(atom(), binary()) -> ok | {error, validate_fail}). -spec(del_forward(atom(), binary()) -> ok | {error, validate_fail}).
del_forward(Name, Topic) -> del_forward(Name, Topic) ->
case catch emqx_topic:validate({filter, Topic}) of try emqx_topic:validate({filter, Topic}) of
true -> true ->
gen_server:call(name(Name), {del_forward, Topic}); gen_server:call(name(Name), {del_forward, Topic})
_ -> catch
_Error:_Reason ->
{error, validate_fail} {error, validate_fail}
end. end.
@ -82,19 +84,21 @@ show_subscriptions(Name) ->
-spec(add_subscription(atom(), binary(), integer()) -> ok | {error, already_exists | validate_fail}). -spec(add_subscription(atom(), binary(), integer()) -> ok | {error, already_exists | validate_fail}).
add_subscription(Name, Topic, QoS) -> add_subscription(Name, Topic, QoS) ->
case catch emqx_topic:validate({filter, Topic}) of try emqx_topic:validate({filter, Topic}) of
true -> true ->
gen_server:call(name(Name), {add_subscription, Topic, QoS}); gen_server:call(name(Name), {add_subscription, Topic, QoS})
{'EXIT', _Reason} -> catch
_Error:_Reason ->
{error, validate_fail} {error, validate_fail}
end. end.
-spec(del_subscription(atom(), binary()) -> ok | {error, validate_fail}). -spec(del_subscription(atom(), binary()) -> ok | {error, validate_fail}).
del_subscription(Name, Topic) -> del_subscription(Name, Topic) ->
case catch emqx_topic:validate({filter, Topic}) of try emqx_topic:validate({filter, Topic}) of
true -> true ->
gen_server:call(name(Name), {del_subscription, Topic}); gen_server:call(name(Name), {del_subscription, Topic})
_ -> catch
error:_Reason ->
{error, validate_fail} {error, validate_fail}
end. end.

View File

@ -27,21 +27,22 @@
start(_, 0, _) -> start(_, 0, _) ->
{ok, #keepalive{}}; {ok, #keepalive{}};
start(StatFun, TimeoutSec, TimeoutMsg) -> start(StatFun, TimeoutSec, TimeoutMsg) ->
case catch StatFun() of try StatFun() of
{ok, StatVal} -> {ok, StatVal} ->
{ok, #keepalive{statfun = StatFun, statval = StatVal, {ok, #keepalive{statfun = StatFun, statval = StatVal,
tsec = TimeoutSec, tmsg = TimeoutMsg, tsec = TimeoutSec, tmsg = TimeoutMsg,
tref = timer(TimeoutSec, TimeoutMsg)}}; tref = timer(TimeoutSec, TimeoutMsg)}};
{error, Error} -> {error, Error} ->
{error, Error}; {error, Error}
{'EXIT', Reason} -> catch
_Error:Reason ->
{error, Reason} {error, Reason}
end. end.
%% @doc Check keepalive, called when timeout... %% @doc Check keepalive, called when timeout...
-spec(check(keepalive()) -> {ok, keepalive()} | {error, term()}). -spec(check(keepalive()) -> {ok, keepalive()} | {error, term()}).
check(KeepAlive = #keepalive{statfun = StatFun, statval = LastVal, repeat = Repeat}) -> check(KeepAlive = #keepalive{statfun = StatFun, statval = LastVal, repeat = Repeat}) ->
case catch StatFun() of try StatFun() of
{ok, NewVal} -> {ok, NewVal} ->
if NewVal =/= LastVal -> if NewVal =/= LastVal ->
{ok, resume(KeepAlive#keepalive{statval = NewVal, repeat = 0})}; {ok, resume(KeepAlive#keepalive{statval = NewVal, repeat = 0})};
@ -51,8 +52,9 @@ check(KeepAlive = #keepalive{statfun = StatFun, statval = LastVal, repeat = Repe
{error, timeout} {error, timeout}
end; end;
{error, Error} -> {error, Error} ->
{error, Error}; {error, Error}
{'EXIT', Reason} -> catch
_Error:Reason ->
{error, Reason} {error, Reason}
end. end.
@ -69,4 +71,3 @@ cancel(_) ->
timer(Secs, Msg) -> timer(Secs, Msg) ->
erlang:send_after(timer:seconds(Secs), self(), Msg). erlang:send_after(timer:seconds(Secs), self(), Msg).

View File

@ -15,6 +15,7 @@
-module(emqx_mountpoint). -module(emqx_mountpoint).
-include("emqx.hrl"). -include("emqx.hrl").
-include("logger.hrl").
-export([mount/2, unmount/2]). -export([mount/2, unmount/2]).
-export([replvar/2]). -export([replvar/2]).
@ -33,9 +34,12 @@ mount(MountPoint, TopicFilters) when is_list(TopicFilters) ->
unmount(undefined, Msg) -> unmount(undefined, Msg) ->
Msg; Msg;
unmount(MountPoint, Msg = #message{topic = Topic}) -> unmount(MountPoint, Msg = #message{topic = Topic}) ->
case catch split_binary(Topic, byte_size(MountPoint)) of try split_binary(Topic, byte_size(MountPoint)) of
{MountPoint, Topic1} -> Msg#message{topic = Topic1}; {MountPoint, Topic1} -> Msg#message{topic = Topic1}
_Other -> Msg catch
_Error:Reason ->
?LOG(error, "Unmount error : ~p", [Reason]),
Msg
end. end.
replvar(undefined, _Vars) -> replvar(undefined, _Vars) ->
@ -49,4 +53,3 @@ feed_var({<<"%u">>, undefined}, MountPoint) ->
MountPoint; MountPoint;
feed_var({<<"%u">>, Username}, MountPoint) -> feed_var({<<"%u">>, Username}, MountPoint) ->
emqx_topic:feed_var(<<"%u">>, Username, MountPoint). emqx_topic:feed_var(<<"%u">>, Username, MountPoint).

View File

@ -245,22 +245,22 @@ received(Packet = ?PACKET(Type), PState) ->
process_packet(Packet1, inc_stats(recv, Type, PState2)) process_packet(Packet1, inc_stats(recv, Type, PState2))
end end
catch catch
error : protocol_error -> error:protocol_error ->
deliver({disconnect, ?RC_PROTOCOL_ERROR}, PState1), deliver({disconnect, ?RC_PROTOCOL_ERROR}, PState1),
{error, protocol_error, PState}; {error, protocol_error, PState};
error : subscription_identifier_invalid -> error:subscription_identifier_invalid ->
deliver({disconnect, ?RC_SUBSCRIPTION_IDENTIFIERS_NOT_SUPPORTED}, PState1), deliver({disconnect, ?RC_SUBSCRIPTION_IDENTIFIERS_NOT_SUPPORTED}, PState1),
{error, subscription_identifier_invalid, PState1}; {error, subscription_identifier_invalid, PState1};
error : topic_alias_invalid -> error:topic_alias_invalid ->
deliver({disconnect, ?RC_TOPIC_ALIAS_INVALID}, PState1), deliver({disconnect, ?RC_TOPIC_ALIAS_INVALID}, PState1),
{error, topic_alias_invalid, PState1}; {error, topic_alias_invalid, PState1};
error : topic_filters_invalid -> error:topic_filters_invalid ->
deliver({disconnect, ?RC_TOPIC_FILTER_INVALID}, PState1), deliver({disconnect, ?RC_TOPIC_FILTER_INVALID}, PState1),
{error, topic_filters_invalid, PState1}; {error, topic_filters_invalid, PState1};
error : topic_name_invalid -> error:topic_name_invalid ->
deliver({disconnect, ?RC_TOPIC_FILTER_INVALID}, PState1), deliver({disconnect, ?RC_TOPIC_FILTER_INVALID}, PState1),
{error, topic_filters_invalid, PState1}; {error, topic_filters_invalid, PState1};
error : Reason -> error:Reason ->
deliver({disconnect, ?RC_MALFORMED_PACKET}, PState1), deliver({disconnect, ?RC_MALFORMED_PACKET}, PState1),
{error, Reason, PState1} {error, Reason, PState1}
end. end.
@ -974,4 +974,3 @@ reason_codes_compat(unsuback, _ReasonCodes, _ProtoVer) ->
undefined; undefined;
reason_codes_compat(PktType, ReasonCodes, _ProtoVer) -> reason_codes_compat(PktType, ReasonCodes, _ProtoVer) ->
[emqx_reason_codes:compat(PktType, RC) || RC <- ReasonCodes]. [emqx_reason_codes:compat(PktType, RC) || RC <- ReasonCodes].

View File

@ -351,30 +351,38 @@ port_info(PortTerm, memory_used) ->
port_info(PortTerm, specific) -> port_info(PortTerm, specific) ->
Port = transform_port(PortTerm), Port = transform_port(PortTerm),
Props = case erlang:port_info(Port, name) of Props = case erlang:port_info(Port, name) of
{_, Type} when Type =:= "udp_inet"; {_, Type} when Type =:= "udp_inet";
Type =:= "tcp_inet"; Type =:= "tcp_inet";
Type =:= "sctp_inet" -> Type =:= "sctp_inet" ->
case catch inet:getstat(Port) of try inet:getstat(Port) of
{ok, Stats} -> [{statistics, Stats}]; {ok, Stats} -> [{statistics, Stats}];
_ -> []
end ++
case catch inet:peername(Port) of
{ok, Peer} -> [{peername, Peer}];
{error, _} -> [] {error, _} -> []
catch
_Error:_Reason -> []
end ++ end ++
case catch inet:sockname(Port) of try inet:peername(Port) of
{ok, Peer} -> [{peername, Peer}];
_ -> []
catch
_Error:_Reason -> []
end ++
try inet:sockname(Port) of
{ok, Local} -> [{sockname, Local}]; {ok, Local} -> [{sockname, Local}];
{error, _} -> [] {error, _} -> []
catch
_Error:_Reason -> []
end ++ end ++
case catch inet:getopts(Port, ?SOCKET_OPTS ) of try inet:getopts(Port, ?SOCKET_OPTS ) of
{ok, Opts} -> [{options, Opts}]; {ok, Opts} -> [{options, Opts}];
{error, _} -> [] {error, _} -> []
catch
_Error:_Reason -> []
end; end;
{_, "efile"} -> {_, "efile"} ->
[]; [];
_ -> _ ->
[] []
end, end,
{specific, Props}; {specific, Props};
port_info(PortTerm, Keys) when is_list(Keys) -> port_info(PortTerm, Keys) when is_list(Keys) ->
Port = transform_port(PortTerm), Port = transform_port(PortTerm),