0

我有一个包装端口的 gen_server。terminate/2它调用gen_server 的回调port_close(Port)以确保端口已关闭。如果端口已经关闭(这会导致 gen_server 停止),我的理解是这会抛出bad_argument异常。为了解决这个问题,我使用了表达式catch port_close(Port)。但是,您猜对了,异常仍在被抛出。

编码:

terminate(Reason, #state{port=Port}) ->
    lager:info("Terminating ~p due to ~p", [?MODULE, Reason]),
    catch port_close(Port).

还有一个例外:

6:31:03.034 [error] CRASH REPORT Process <0.69.0> with 1 neighbours exited with reason: bad argument in call to erlang:port_close(#Port<0.3906>) in my_gen_server:terminate/2 line 62 in gen_server:terminate/6 line 725
** exception error: bad argument
     in function  port_close/1
        called as port_close(#Port<0.3906>)
     in call from my_gen_server:terminate/2 (src/my_gen_server.erl, line 62)
     in call from gen_server:terminate/6 (gen_server.erl, line 722)
     in call from proc_lib:init_p_do_apply/3 (proc_lib.erl, line 227)

是否会出现相同的错误Reason = normal | term()

对于为什么没有被抓住的任何建议,我将非常感谢!

4

1 回答 1

1

好吧,答案是我需要一个不同的返回值,在这种情况下ok

terminate(Reason, #state{port=Port}) ->
    lager:info("Terminating ~p due to ~p", [?MODULE, Reason]),
    catch port_close(Port),
    ok.

我仍然有点困惑,因为文档说明了terminate/2这一点The return value is ignored.

于 2013-06-12T20:18:52.627 回答