gpt4 book ai didi

exception-handling - Erlang 错误处理哲学 - case vs throw

转载 作者:行者123 更新时间:2023-12-04 07:51:04 24 4
gpt4 key购买 nike

我正在用 Erlang 编写 REST 服务,需要先验证接收到的数据,然后再将其传递给其他内部函数进行进一步处理;为了做到这一点,我目前正在使用嵌套 case像这样的表达:

case all_args_defined(Args) of
true ->
ActionSuccess = action(Args),

case ActionSuccess of
{ok, _} -> ...;
{fail, reason} -> {fail, reason}
end,
_ ->
{fail, "args not defined"}
end,
...

我意识到这有点难看,但这样我就可以提供详细的错误消息。此外,我不认为通常的让它崩溃的哲学在这里适用 - 我不希望我的 REST 服务崩溃并在每次有人向它抛出无效参数时重新启动。

但是,我正在考虑放弃所有这些 cases赞成一把伞 try/catch拦截任何 badmatch错误 - 这行得通吗?
fun() ->
true = all_args_defined(Args),
{ok, _} = action(Args).

%% somewhere else
catch fun().

最佳答案

由于您想要实现的是错误报告,因此您应该围绕操作的执行和结果的报告来构建事物。也许是这样的:


execute(Action, Args) ->
try
check_args(Args),
Result = action(Action, Args),
send_result(Result)
catch
throw:{fail, Reason} ->
report_error(Reason);
ExceptionClass:Term ->
%% catch-all for all other unexpected exceptions
Trace = erlang:get_stacktrace(),
report_error({crash, ExceptionClass, Term, Trace})
end.

%% all of these throw {fail, Reason} if they detect something fishy
%% and otherwise they return some value as result (or just crash)
action(foo, [X1, X2]) -> ...;
action(foo, Args) -> throw({fail, {bad_arity, foo, 2, Args}});
action(...) -> ...

%% this handles the formatting of all possible errors
report_error({bad_arity, Action, Arity, Args}) ->
send_error(io_lib:format("wrong number of arguments for ~w: "
"expected ~w, but got ~w",
[Action, Arity, length(Args)]));
report_error(...) -> ...;
report_error({crash, Class, Term, Trace}) ->
send_error(io_lib:format("internal error: "
"~w:~w~nstacktrace:~n~p~n",
[Class, Term, Trace])).

关于exception-handling - Erlang 错误处理哲学 - case vs throw,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6859645/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com