Skip to content

Commit 906cc68

Browse files
committed
allow overriding handle_errors after using Sentry.Plug
mention this in docs, as well as a fact that using Sentry.Plug does not retain Plug.ErrorHandler default behaviour of sending "Something went wrong" as a response (because Sentry.Plug does not call `super()` in it's handle_errors/2 implementation)
1 parent 747964b commit 906cc68

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

lib/sentry/plug.ex

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,16 @@ if Code.ensure_loaded?(Plug) do
1515
use Plug.ErrorHandler
1616
use Sentry.Plug
1717
18+
Note that using Sentry.Plug will override default behaviour of Plug.ErrorHandler - it will
19+
no longer write "Something went wrong" as a response.
20+
If you want to retain this behaviour, or in general to add custom logic on top of sending event to sentry,
21+
you can do it like this:
22+
23+
defp handle_errors(conn, %{kind: _kind, reason: _reason, stack: _stack} = error) do
24+
super(conn, error)
25+
send_resp(conn, conn.status, "Something went wrong")
26+
end
27+
1828
### Sending Post Body Params
1929
2030
In order to send post body parameters you should first scrub them of sensitive
@@ -131,6 +141,8 @@ if Code.ensure_loaded?(Plug) do
131141
error_type: kind
132142
)
133143
end
144+
145+
defoverridable handle_errors: 2
134146
end
135147
end
136148

test/plug_test.exs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,38 @@ defmodule Sentry.PlugTest do
1717
)
1818
end
1919

20+
test "overriding handle_errors/2" do
21+
Code.compile_string("""
22+
defmodule DefaultConfigApp do
23+
use Plug.Router
24+
use Plug.ErrorHandler
25+
use Sentry.Plug
26+
plug :match
27+
plug :dispatch
28+
forward("/", to: Sentry.ExampleApp)
29+
30+
defp handle_errors(conn, %{kind: _kind, reason: _reason, stack: _stack} = error) do
31+
super(conn, error)
32+
send_resp(conn, conn.status, "Something went terribly wrong")
33+
end
34+
end
35+
""")
36+
37+
bypass = Bypass.open()
38+
39+
Bypass.expect(bypass, fn conn ->
40+
Plug.Conn.resp(conn, 200, ~s<{"id": "340"}>)
41+
end)
42+
43+
modify_env(:sentry, dsn: "http://public:secret@localhost:#{bypass.port}/1")
44+
45+
conn = conn(:post, "/error_route", %{})
46+
assert_raise(RuntimeError, "Error", fn ->
47+
DefaultConfigApp.call(conn, [])
48+
end)
49+
assert {500, _headers, "Something went terribly wrong"} = sent_resp(conn)
50+
end
51+
2052
test "default data scrubbing" do
2153
Code.compile_string("""
2254
defmodule DefaultConfigApp do

0 commit comments

Comments
 (0)