Skip to content

Instantly share code, notes, and snippets.

@teamon
Created July 14, 2017 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teamon/ec428154d4106370b8e75c57e2067901 to your computer and use it in GitHub Desktop.
Save teamon/ec428154d4106370b8e75c57e2067901 to your computer and use it in GitHub Desktop.
defmodule Appsignal.Plug.JSExceptionCatcher do
@behaviour Plug
import Plug.Conn
alias Appsignal.Transaction
@defaults [
path: "/appsignal_error_catcher",
namespace: :frontend
]
def init(opts), do: Keyword.merge(@defaults, opts)
def call(conn, opts) do
if matches?(conn, opts[:path]) do
handle(conn, opts[:namespace])
else
conn
end
end
defp handle(conn, namespace) do
conn
|> fetch_session()
|> send_error(namespace)
|> send_resp(200, "OK")
|> halt()
end
defp send_error(%{params: params} = conn, namespace) do
# run in separate process to not inherit any transaction details from phoenix
spawn fn ->
if Transaction.lookup_or_create_transaction(self(), namespace) != nil do
Transaction.set_error(params["name"], params["message"], params["backtrace"])
Transaction.set_meta_data(params["metadata"])
Transaction.set_sample_data("environment", params["environment"])
Transaction.set_sample_data("session_data", conn.private[:plug_session])
Transaction.finish()
Transaction.complete()
end
end
conn
end
defp matches?(conn, path), do: String.starts_with?(conn.request_path, path)
end
defmodule Appsignal.Tesla do
import Appsignal.Instrumentation.Helpers, only: [instrument: 3]
def call(env, next, _opts) do
verb = env.method |> to_string |> String.upcase
instrument "net.http", "#{verb} #{env.url}", fn ->
Tesla.run(env, next)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment