错误处理

Erlang运行时错误有两种处理方式:

  • 捕获异常并防止终止执行线程
  • 随其失效,通过进程相连和监控的选择来让系统其他部分来处理恢复

使用 try ... catch

使用形式:

try Exprs of
    Pattern1 [when GuardSeq1] ->
        Body1;
    ...;
    PatternN [when GuardSeqN] ->
        BodyN
catch
    [Class1:]ExceptionPattern1 [when ExceptionGuardSeq1] ->
        ExceptionBody1;
    ...;
    [ClassN:]ExceptionPatternN [when ExceptionGuardSeqN] ->
        ExceptionBodyN
after
    AfterBody
end

Exceptions

Class Origin
error Run-time error, for example, 1+a, or the process called erlang:error/1,2 (new in Erlang 5.4/OTP R10B)
exit The process called exit/1
throw The process called throw/1

进程链接和退出信号

link/1 可以与指定的进程创建双向联系, unlink/1 移除链接

spawn_link/3 = spawn/3 + link/1 ,并具有原子性

如果一个链接进程异常终止,退出信号就会发送到与这个终止进程相连的所有进程。退出信号是具有{'EXIT',Pid,Reason}格式的元组。

exit(Reason)可以使调用进程终止,产生对应退出信号。

捕捉退出信号

进程可以通过设定进程标识trap_exit,然后执行函数调用process_flag(trap_exit,true)来捕获退出信号,这样退出信号就会保存在进程信箱中了。

想停止捕捉退出信号,可以使用process_flag(trap_exit,false),不过切换trap_exit不是好的软件实践。

监控内置函数

单向监控进程,可以使用erlang:monitor(process,Proc)创建监控进程, Proc可以是Pid或别名。进程终止时,消息{'DOWN',Reference,process,Pid,Reason}会发送到监控进程。

erlang:demonitor(Reference,[flusg]) 可以关闭监控并清除对应得'DOWN'消息