我正在编写一个 gen_server,我们将称之为 gen_server_db,它并没有什么特别之处。它使用的库 (emysql) 有可能在尝试查找数据库服务器时遇到连接失败(在 gen_server_db:init() 中)。当我捕捉到异常并尝试将某些内容打印到控制台时,我得到了 zip。在下面的代码示例中,两个 io:format 消息都无法到达控制台。我似乎记得很久以前听到过这个的原因,但我不记得为什么。
init(Args) ->
% I've condensed the way I actually get this stuff to one line, but if I have a
% database online I connect properly, so I know that I'm getting the Host, User, etc.
{Host, User, Password, DB, PoolSize} = application:get_env(gen_server_db, config),
init_mysql_connection(gen_server_db_pool, PoolSize, User, Password, Host, DB),
% When the net connection to the db is down, I never get here.
ok.
init_mysql_connection(bgo_db_pool, PoolSize, User, Password, Host, DB) ->
try
emysql:add_pool(bgo_db_pool, PoolSize, User, Password, Host, 3306, DB, utf8)
catch
exit:failed_to_connect_to_database ->
io:format("Cannot connect to the mysql database server. Retrying in 1 sec.~n"),
timer:sleep(1000),
init_mysql_connection(bgo_db_pool, PoolSize, User, Password, Host, DB);
Error:Reason ->
io:format("Database connection error: ~p:~p~n", [Error, Reason]),
1/0
end.