Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use __STACKTRACE__ in case statement or controllers

I'm struggling with a deprecation warning in my Phoenix app : 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.

The thing is, I'm using Rollbax as described in their documentation: Rollbax.report(:error, ArgumentError.exception("oops"), System.stacktrace()) and it feels kind of weird to wrap every case statement I'm doing in a try/rescue block. For example this one:

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

I'm not sure how I can have those different report in a single rescue... What would be the proper way to write this one?

like image 439
Vanessa Avatar asked Mar 15 '19 10:03

Vanessa


1 Answers

Wrap the whole case statement:

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
like image 173
Aleksei Matiushkin Avatar answered Sep 20 '22 12:09

Aleksei Matiushkin