Plug and Phoenix
Learn how to capture errors and their context in Plug pipelines and Phoenix applications.
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:
- Add
Sentry.PlugCapture
above theuse Phoenix.Endpoint
line in your endpoint file. - Add
Sentry.PlugContext
belowPlug.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're also using Phoenix LiveView, consider also setting up your LiveViews to use the Sentry.LiveViewHook
hook (available in the Sentry SDK versions 10.5.0
and higher):
defmodule MyAppWeb do
def live_view do
quote do
use Phoenix.LiveView
on_mount Sentry.LiveViewHook
end
end
end
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})
~E"""
<script src="https://browser.sentry-cdn.com/5.9.1/bundle.min.js" integrity="sha384-/x1aHz0nKRd6zVUazsV6CbQvjJvr6zQL2CHbQZf3yoLkezyEtZUpqUNnOLW9Nt3v" crossorigin="anonymous"></script>
<script>
Sentry.init({ dsn: '<%= Sentry.get_dsn() %>' });
Sentry.showReportDialog(<%= raw opts %>)
</script>
"""
_ ->
"Error"
end
end
end
If you have a non-Phoenix application, follow these steps to configure the Plug integration:
- Add
Sentry.PlugCapture
at the top of your Plug application. - Add
Sentry.PlugContext
belowPlug.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
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").