Skip to content

Commit

Permalink
Merge branch 'main' into throwing-plug
Browse files Browse the repository at this point in the history
  • Loading branch information
grzuy committed Nov 12, 2024
2 parents e58aeb7 + 3e12dd4 commit ae7e29a
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 2 deletions.
10 changes: 9 additions & 1 deletion lib/bandit/pipeline.ex
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,12 @@ defmodule Bandit.Pipeline do
status = reason |> 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(kind, reason, stacktrace), domain: [:bandit])
Logger.error(
Exception.format(kind, reason, stacktrace),
domain: [:bandit],
crash_reason: crash_reason(kind, reason, stacktrace)
)

Bandit.HTTPTransport.send_on_error(transport, reason)
{:error, reason}
else
Expand All @@ -251,4 +256,7 @@ defmodule Bandit.Pipeline do
end

defp do_maybe_log_error(_error, _stacktrace, false), do: :ok

defp crash_reason(:throw, reason, stacktrace), do: {{:nocatch, reason}, stacktrace}
defp crash_reason(_, reason, stacktrace), do: {reason, stacktrace}
end
2 changes: 1 addition & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ defmodule Bandit.MixProject do
{:thousand_island, "~> 1.0"},
{:plug, "~> 1.14"},
{:websock, "~> 0.5"},
{:hpax, "~> 1.0.0"},
{:hpax, "~> 1.0"},
{:telemetry, "~> 0.4 or ~> 1.0"},
{:req, "~> 0.3", only: [:dev, :test]},
{:machete, ">= 0.0.0", only: [:dev, :test]},
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 ae7e29a

Please sign in to comment.