venkatd

venkatd

Best practices on exception handling and tracking (let it crash vs. try catch tradeoffs)

I have some code that allows me to run a series of functions. I currently surround the execution itself by a try-catch because I don’t want one execution crashing to cause all future executions to crash.

defmodule ES.Queue do
  use GenServer

  def start_link(base_opts, opts \\ []) do
    defaults = [log_success: &noop/1, log_failure: &noop/1, timeout: 10_000]

    {queue_opts, genserver_opts} =
      defaults
      |> Keyword.merge(base_opts)
      |> Keyword.merge(opts)
      |> Keyword.split([:queue_name, :timeout, :log_success, :log_failure])

    GenServer.start_link(__MODULE__, Map.new(queue_opts), genserver_opts)
  end

  def run(pid, func), do: GenServer.call(pid, {:run, func}, 60_000)

  def init(%{timeout: timeout}=state) do
    {:ok, state, timeout}
  end

  def handle_call({:run, func}, _from, %{queue_name: queue_name, timeout: timeout, log_success: log_success, log_failure: log_failure}=state) do
    resp =
      try do
        t1 = :erlang.monotonic_time()
        val = execute(func)
        t2 = :erlang.monotonic_time()
        ms_taken = :erlang.convert_time_unit(t2 - t1, :native, :millisecond)
        log_success.({queue_name, func, ms_taken})
        val
      catch
        type, error ->
          log_failure.({type, error, System.stacktrace()})
      end
    {:reply, resp, state, timeout}
  end
  def handle_call(:inspect, _from, %{timeout: timeout}=state) do
    {:reply, Kernel.inspect(state), state, timeout}
  end

  def execute(func) when is_function(func), do: func.()
  def execute({mod, func}), do: apply(mod, func, [])
  def execute({mod, func, args}), do: apply(mod, func, args)

  def noop(_), do: nil

  def handle_info(:timeout, state) do
    {:stop, :normal, state}
  end

end

However there are a few problems with this approach:

  • When an exception occurs during a mix test, the errors get swallowed. It becomes much harder to track down the error vs. when I remove the try catch.
  • If this code is in production, exceptions won’t get logged out or sent to an error reporting service like Rollbar

Basically, I still want exceptions to be loud. I still want the red error with the stacktrace to be printed out to the logs when I am running tests. I still want errors to get reported to an error reporting service while the app is running in production. What are some good options for this?

Thanks!

Most Liked

cmkarlsson

cmkarlsson

How about doing the execution in another process? It is not uncommon to do this for things that can fail. Your GenServer spawns and waits for the result from the execution. It also monitors the newly spawned process for failures. The execute are still synchronized, the monitoring GenServer will not fail and continues with the other cases even if one fails.

I’m not sure what sort of error logging you are looking for when something crashes but perhaps if the execution is done according to OTP standards (either a GenServer or a process started with proc_lib) I think you may get SASL logging which Logger may pick up.

sasajuric

sasajuric

Author of Elixir In Action

You can log the error directly like this:

try do
  # ...
catch
  type, error ->
    Logger.error(Exception.format(type, error, __STACKTRACE__))
end

That said, I agree with @cmkarlsson’s proposal. If you want to ensure that “execution” doesn’t take the GenServer down, doing it in a separate process would give you the strongest guarantees of that.

Where Next?

Popular in Questions Top

chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29603 241
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 43487 311
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 54120 245
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement