6

我在我的 Phoenix 应用程序中遇到弃用警告:System.stacktrace/0 outside of rescue/catch clauses is deprecated. If you want to support only Elixir v1.7+, you must access __STACKTRACE__ inside a rescue/catch. If you want to support earlier Elixir versions, move System.stacktrace/0 inside a rescue/catch.

问题是,我正在使用 Rollbax,如他们的文档中所述:Rollbax.report(:error, ArgumentError.exception("oops"), System.stacktrace())将我正在执行的每个 case 语句包装在 try/rescue 块中感觉有点奇怪。比如这个:

case (SOME_URL |> HTTPoison.get([], [ ssl: [{:versions, [:'tlsv1.2']}] ])) do
      {:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
        Poison.decode!(body, [keys: :atoms])
      {:ok, %HTTPoison.Response{status_code: 404}} ->
        Rollbax.report(:error, :not_found, System.stacktrace(), %{reason: "Not found"})
      {:ok, %HTTPoison.Response{status_code: 503}} ->
        {:error, :ehostunreach}
      {:error, %HTTPoison.Error{reason: :ehostunreach}} ->
        {:error, :ehostunreach}
      {:error, %HTTPoison.Error{reason: :timeout}} ->
        Rollbax.report(:error, :timeout, System.stacktrace(), %{reason: :timeout})
      {:error, %HTTPoison.Error{reason: reason}} ->
        Rollbax.report(:error, :unknown, System.stacktrace(), %{reason: reason})
        {:error, reason}
    end

我不确定如何在一次救援中获得这些不同的报告......写这个的正确方法是什么?

4

1 回答 1

3

包装整个case语句:

try do
  #                           ⇓⇓⇓⇓ NOTE BANG
  case (SOME_URL |> HTTPoison.get!([], [ ssl: [{:versions, [:'tlsv1.2']}] ])) do
    %HTTPoison.Response{status_code: 200, body: body} ->
      Poison.decode!(body, [keys: :atoms])
    %HTTPoison.Response{status_code: 404} ->
      raise HTTPoison.Error, reason: :not_found
    %HTTPoison.Response{status_code: 503} ->
      {:error, :ehostunreach}
rescue
  e in [HTTPoison.Error] ->
    case e do
      %HTTPoison.Error{reason: :not_found} ->
        Rollbax.report(:error, :not_found, __STACKTRACE__, %{reason: "Not found"})
      %HTTPoison.Error{reason: :ehostunreach} ->
        {:error, :ehostunreach}
      %HTTPoison.Error{reason: :timeout} ->
        Rollbax.report(:error, :timeout, __STACKTRACE__, %{reason: :timeout})
      %HTTPoison.Error{reason: reason} ->
        Rollbax.report(:error, :unknown, __STACKTRACE__, %{reason: reason})
        {:error, reason}
    end
end
于 2019-03-15T10:14:05.167 回答