[英]Elixir - Catching :enetunreach and :ehostunreach errors
我有一個 GenServer 每隔 x 秒創建一個與遠程主機的連接,我很難捕捉到與網絡相關的錯誤(更具體地說是:.netunreach
和:ehostunreach
)。
** (EXIT from #PID<0.327.0>) shell process exited with reason: :enetunreach
** (EXIT from #PID<0.327.0>) shell process exited with reason: :ehostunreach
我正在使用的基本代碼基本上是這樣的:
try do
# Create Connection
catch
type, call ->
IO.inspect("Something happened while trying to connect.")
IO.inspect(type)
IO.inspect(call)
end
已經嘗試過catch
和raise
但它總是會因這些錯誤而失敗。
您應該弄清楚的最重要的事情是進程如何在 OTP actor model 中生存。該進程不能干擾另一個進程的行為,包括但不限於捕獲那里拋出/引發的異常。
考慮以下人為的示例,模仿您遇到的問題。
defmodule M do
use GenServer
# @impl GenServer
# def init(:ok), do: {:ok, Process.flag(:trap_exit, true)}
# @impl GenServer
# def handle_info({:EXIT, _pid, reason}, state),
# do: {:noreply, IO.inspect("CAUGHT!")}
@impl GenServer
def handle_call(:test, _from, state),
do: {:reply, Process.exit(self(), :foo), state}
end
{:ok, pid} = GenServer.start_link M, :ok
GenServer.call(pid, :test)
在您取消注釋注釋行之前,您會像[error] GenServer #PID<0.132.0> terminating
一樣返回。 您必須控制(實際上不是控制,只是監督)另一個進程的流程的唯一可能性是監視它。
也就是說,您需要監控您啟動的進程,將您的進程設置為捕獲退出並對收到的{:EXIT, _, _}
消息做出相應反應。
TL;DR try/1
只會捕獲同一進程中引發的異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.