Erlang gen_server:如何捕获错误?

时间:2019-02-23 11:48:13

标签: erlang otp gen-server

我是Erlang开发的新手,并且对流程关系感兴趣。

如果我们将两个进程P1和P2与process_flag(trap_exit, true)链接,并使用Pid ! msgreceive .. after .. end这样的构造,则第二个进程P2可能会捕获badarith这样的P1错误

但是,如果我们使用与P2链接的gen_server进程P1,则-P1在P2失败后终止。

那么,如何使用gen_server捕获exit()错误?

谢谢!

P.S。测试代码。

P1:

-module(test1).
-compile(export_all).
-behaviour(gen_server).

start() ->
  gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

init([]) -> Link = self(),
            spawn(fun() ->
              process_flag(trap_exit, true),
              link(Link),
              test2:start(Link)
            end),
            {ok, "lol"}.

handle_call(stop, From, State) ->
  io:fwrite("Stop from ~p. State = ~p~n",[From, State]),
  {stop, normal, "stopped", State};

handle_call(MSG, From, State) ->
  io:fwrite("MSG ~p from ~p. State = ~p~n",[MSG, From, State]),
  {reply, "okay", State}.

handle_info(Info, State) -> io:fwrite("Info message ~p. State = ~p~n",[Info, State]), {noreply, State}.

terminate(Reason, State) -> io:fwrite("Reason ~p. State ~p~n",[Reason, State]), ok.

P2:

-module(test2).
-compile(export_all).

start(Mod) ->
  io:fwrite("test2: Im starting with Pid=~p~n",[self()]),
  receiver(Mod).

receiver(Mod)->
  receive
    stop ->
      Mod ! {goodbye},
      io:fwrite("Pid: I exit~n"),
      exit(badarith);
    X ->
      io:fwrite("Pid: I received ~p~n",[X])
  end.

结果:test2进程死机后,test1进程失败。

38> 
38> c(test1).                    
test1.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,test1}
39> c(test2).                    
test2.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,test2}
40> test1:start().               
test2: Im starting with Pid=<0.200.0>
{ok,<0.199.0>}
41> <0.200.0> ! stop.            
Pid: I exit
Info message {goodbye}. State = "lol"
stop
** exception exit: badarith
42> gen_server:call(test1, stop).
** exception exit: {noproc,{gen_server,call,[test1,stop]}}
     in function  gen_server:call/2 (gen_server.erl, line 215)
43> 

1 个答案:

答案 0 :(得分:5)

链接是双向的,但不是陷阱出口。您需要在P1中调用process_flag(trap_exit, true)(您的当前代码在P2中进行了调用),然后处理{'EXIT', FromPid, Reason}handle_info形式的消息(将P2的pid放入State中帮助)。

在这种情况下,如果P1停止,P2停止是有意义的,否则我建议使用monitor而不是链接。

旁注:

  1. 使用spawn_link代替spawn + link

  2. spawn移到test2:start中是更好的样式。