Skip to content

Commit

Permalink
feat: lets :logger handlers know about the original exception (#417)
Browse files Browse the repository at this point in the history
  • Loading branch information
grzuy authored Nov 12, 2024
1 parent 93cf850 commit 3e12dd4
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/bandit/pipeline.ex
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,12 @@ defmodule Bandit.Pipeline do
status = error |> Plug.Exception.status() |> Plug.Conn.Status.code()

if status in Keyword.get(opts.http, :log_exceptions_with_status_codes, 500..599) do
Logger.error(Exception.format(:error, error, stacktrace), domain: [:bandit])
Logger.error(
Exception.format(:error, error, stacktrace),
domain: [:bandit],
crash_reason: {error, stacktrace}
)

Bandit.HTTPTransport.send_on_error(transport, error)
{:error, error}
else
Expand Down
27 changes: 27 additions & 0 deletions test/bandit/http1/request_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,33 @@ defmodule HTTP1RequestTest do
assert output =~ "(RuntimeError) boom"
end

@tag capture_log: true
test "it should provide useful metadata to logger handlers when unknown exceptions are raised",
context do
defmodule TestLoggerHandler do
def log(log_event, %{config: %{test_pid: test_pid}}) do
send(test_pid, {:log_event, log_event})
end
end

:logger.add_handler(
TestLoggerHandler,
TestLoggerHandler,
%{level: :error, config: %{test_pid: self()}}
)

{:ok, response} = Req.get(context.req, url: "/unknown_crasher")
assert response.status == 500

assert_receive {:log_event, log_event}

assert %{
level: :error,
msg: _msg,
meta: %{crash_reason: {%RuntimeError{message: "boom"}, [_ | _] = _stacktrace}}
} = log_event
end

def unknown_crasher(_conn) do
raise "boom"
end
Expand Down

0 comments on commit 3e12dd4

Please sign in to comment.