Joe Armstrong 的建议之一:将程序成功案例代码与错误处理分开。你可以这样做
create_user(Email, UserName, Password) ->
try
ok = new_email(Email),
ok = valid_user_name(UserName),
ok = new_user(UserName),
ok = strong_password(Password),
...
_create_user(Email, UserName, Password)
catch
error:{badmatch, email_in_use} -> do_something();
error:{badmatch, invalid_user_name} -> do_something();
error:{badmatch, user_exists} -> do_something();
error:{badmatch, weak_password} -> do_something();
...
end.
请注意,您可以从更好的 create_user 函数中捕获所有错误。
create_user(Email, UserName, Password) ->
ok = new_email(Email),
ok = valid_user_name(UserName),
ok = new_user(UserName),
ok = strong_password(Password),
...
_create_user(Email, UserName, Password).
main() ->
try
...
some_function_where_create_user_is_called(),
...
catch
...
error:{badmatch, email_in_use} -> do_something();
error:{badmatch, invalid_user_name} -> do_something();
error:{badmatch, user_exists} -> do_something();
error:{badmatch, weak_password} -> do_something();
...
end.
模式匹配是 Erlang 中最酷的事情之一。请注意,您可以将您的标签包含在错误匹配错误中
{my_tag, ok} = {my_tag, my_call(X)}
和自定义数据
{my_tag, ok, X} = {my_tag, my_call(X), X}
如果异常对您来说足够快取决于您的期望。在我的 2.2GHz Core2 Duo Intel 上的速度:一秒钟内大约 200 万次异常(0.47us)与 600 万次成功(外部)函数调用(0.146us)相比——可以猜测异常处理大约需要 0.32us。在本机代码中,它是每秒 6.8 对 4700 万,处理可能需要大约 0.125us。try-catch 构造可能会有一些额外的成本,在本机和字节码中成功调用函数的成本约为 5-10%。