Skip to content

Commit b1c8b6e

Browse files
Merge pull request #251 from getsentry/report-spawned-errors
report spawned errors
2 parents cd9ed8f + d7cfaa1 commit b1c8b6e

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

lib/sentry/logger.ex

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,23 @@ defmodule Sentry.Logger do
4747
{:ok, state}
4848
end
4949

50+
def handle_event({:error, _gl, {_pid, _type, [pid, {exception, stack}]} = info}, state)
51+
when is_list(stack) and is_pid(pid) do
52+
try do
53+
opts =
54+
Keyword.put([], :event_source, :logger)
55+
|> Keyword.put(:stacktrace, stack)
56+
|> Keyword.put(:error_type, :error)
57+
58+
Sentry.capture_exception(exception, opts)
59+
rescue
60+
ex ->
61+
Logger.warn(fn -> "Unable to notify Sentry due to #{inspect(ex)}! #{inspect(info)}" end)
62+
end
63+
64+
{:ok, state}
65+
end
66+
5067
def handle_event({:error_report, _gl, {_pid, _type, [message | _]}}, state)
5168
when is_list(message) do
5269
try do

test/logger_test.exs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,4 +206,29 @@ defmodule Sentry.LoggerTest do
206206

207207
:error_logger.delete_report_handler(Sentry.Logger)
208208
end
209+
210+
test "captures errors from spawn() in Plug app" do
211+
bypass = Bypass.open()
212+
pid = self()
213+
214+
Bypass.expect(bypass, fn conn ->
215+
{:ok, body, conn} = Plug.Conn.read_body(conn)
216+
json = Poison.decode!(body)
217+
assert length(json["stacktrace"]["frames"]) == 1
218+
assert List.first(json["stacktrace"]["frames"])["filename"] == "test/support/test_plug.ex"
219+
send(pid, "API called")
220+
Plug.Conn.resp(conn, 200, ~s<{"id": "340"}>)
221+
end)
222+
223+
modify_env(:sentry, dsn: "http://public:secret@localhost:#{bypass.port}/1")
224+
:error_logger.add_report_handler(Sentry.Logger)
225+
226+
capture_log(fn ->
227+
Plug.Test.conn(:get, "/spawn_error_route")
228+
|> Sentry.ExampleApp.call([])
229+
230+
assert_receive "API called"
231+
:error_logger.delete_report_handler(Sentry.Logger)
232+
end)
233+
end
209234
end

test/support/test_plug.ex

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,14 @@ defmodule Sentry.ExampleApp do
1919
raise RuntimeError, "Error"
2020
end
2121

22+
get "/spawn_error_route" do
23+
spawn(fn ->
24+
raise "Error"
25+
end)
26+
27+
send_resp(conn, 200, "")
28+
end
29+
2230
match "/error_route" do
2331
_ = conn
2432
raise RuntimeError, "Error"

0 commit comments

Comments
 (0)