Plug and Phoenix

You can capture errors in Plug and Phoenix applications with Sentry.PlugContext and Sentry.PlugCapture.

Sentry.PlugContext adds contextual metadata from the current request, which is then included in errors that are captured and reported by Sentry.PlugCapture.

If you are using Phoenix, follow these steps to add the Plug integration:

  1. Add Sentry.PlugCapture above the use Phoenix.Endpoint line in your endpoint file.
  2. Add Sentry.PlugContext below Plug.Parsers.
 defmodule MyAppWeb.Endpoint
+  use Sentry.PlugCapture
   use Phoenix.Endpoint, otp_app: :my_app

   # ...

   plug Plug.Parsers,
     parsers: [:urlencoded, :multipart, :json],
     pass: ["*/*"],
     json_decoder: Phoenix.json_library()

+  plug Sentry.PlugContext

If you would like to capture user feedback, the Sentry.get_last_event_id_and_source/0 function can be used to see if Sentry has sent an event within the current Plug process (and get the source of that event). :plug will be the source for events coming from Sentry.PlugCapture. The options described in the Sentry documentation linked above can be encoded into the response as well.

Below is an example Phoenix application setup that displays the user feedback form on 500 responses on requests accepting HTML:

defmodule MyAppWeb.ErrorView do
  # ...

  def render("500.html", _assigns) do
    case Sentry.get_last_event_id_and_source() do
      {event_id, :plug} when is_binary(event_id) ->
        opts = Jason.encode!(%{eventId: event_id})

        <script src="" integrity="sha384-/x1aHz0nKRd6zVUazsV6CbQvjJvr6zQL2CHbQZf3yoLkezyEtZUpqUNnOLW9Nt3v" crossorigin="anonymous"></script>
          Sentry.init({ dsn: '<%= Sentry.Config.dsn() %>' });
          Sentry.showReportDialog(<%= raw opts %>)

      _ ->

If you have a non-Phoenix application, follow these steps to configure the Plug integration:

  1. Add Sentry.PlugCapture at the top of your Plug application.
  2. Add Sentry.PlugContext below Plug.Parsers (if it is in your stack).
 defmodule MyApp.Router do
   use Plug.Router
+  use Sentry.PlugCapture

   # ...

   plug Plug.Parsers,
     parsers: [:urlencoded, :multipart]

+  plug Sentry.PlugContext
Help improve this content
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").