catch port_close(Port)不会阻止抛出异常

时间:2013-06-10 23:41:09

标签: erlang otp

我有一个包装端口的gen_server。 gen_server的terminate/2回调调用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()

是否会出现同样的错误

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

1 个答案:

答案 0 :(得分: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. {{1}} {{1}} {{}}}以来,我仍然感到有些困惑