From b23b8b0987f842d05d433a7aac5942c12b8680e0 Mon Sep 17 00:00:00 2001 From: martosaur Date: Tue, 17 Jun 2025 22:12:56 -0700 Subject: [PATCH] Ensure crash_reason is a two-element tuple for exit case --- lib/plug/cowboy/translator.ex | 9 +++++++- test/plug/cowboy/translator_test.exs | 34 ++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/lib/plug/cowboy/translator.ex b/lib/plug/cowboy/translator.ex index 740af6c..bb5885b 100644 --- a/lib/plug/cowboy/translator.ex +++ b/lib/plug/cowboy/translator.ex @@ -51,9 +51,16 @@ defmodule Plug.Cowboy.Translator do | Exception.format(:exit, reason, []) ] + crash_reason = + case reason do + {exception, _stack} when is_exception(exception) -> reason + {{:nocatch, _value}, _stack} -> reason + exit_reason -> {exit_reason, []} + end + metadata = [ - crash_reason: reason, + crash_reason: crash_reason, domain: [:cowboy] ] ++ maybe_conn_metadata(conn) diff --git a/test/plug/cowboy/translator_test.exs b/test/plug/cowboy/translator_test.exs index d416df1..fca0043 100644 --- a/test/plug/cowboy/translator_test.exs +++ b/test/plug/cowboy/translator_test.exs @@ -19,6 +19,14 @@ defmodule Plug.Cowboy.TranslatorTest do fn -> GenServer.call(:i_dont_exist, :ok) end |> Task.async() |> Task.await() end + def call(%{path_info: ["exit"]}, _opts) do + exit({:error, ["unfortunate shape"]}) + end + + def call(%{path_info: ["throw"]}, _opts) do + throw("catch!") + end + @metadata_log_opts format: {__MODULE__, :metadata}, metadata: [:conn, :crash_reason, :domain] def metadata(_log_level, _message, _timestamp, metadata) do @@ -144,4 +152,30 @@ defmodule Plug.Cowboy.TranslatorTest do assert metadata =~ "{GenServer, :call" assert metadata =~ "domain: [:cowboy]" end + + test "metadata in ranch/cowboy exit logs" do + {:ok, _pid} = Plug.Cowboy.http(__MODULE__, [], port: 9005) + + metadata = + capture_log(@metadata_log_opts, fn -> + :hackney.get("http://127.0.0.1:9005/exit", [], "", []) + Plug.Cowboy.shutdown(__MODULE__.HTTP) + end) + + assert metadata =~ "crash_reason: {{:error, [\"unfortunate shape\"]}, []}" + assert metadata =~ "domain: [:cowboy]" + end + + test "metadata in ranch/cowboy throw logs" do + {:ok, _pid} = Plug.Cowboy.http(__MODULE__, [], port: 9005) + + metadata = + capture_log(@metadata_log_opts, fn -> + :hackney.get("http://127.0.0.1:9005/throw", [], "", []) + Plug.Cowboy.shutdown(__MODULE__.HTTP) + end) + + assert metadata =~ "crash_reason: {{:nocatch, \"catch!\"}, " + assert metadata =~ "domain: [:cowboy]" + end end