Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add notice_error function for rescued exceptions #470

Merged
merged 1 commit into from
Jan 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions lib/new_relic.ex
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,25 @@ defmodule NewRelic do
defdelegate increment_custom_metric(name, count \\ 1),
to: NewRelic.Harvest.Collector.Metric.Harvester

@doc """
Report an Exception inside a Transaction.

This should only be used when you `rescue` an exception inside a Transaction,
but still want to report it. All un-rescued exceptions are already reported as errors.

## Example

```elixir
try do
raise RuntimeError
rescue
exception -> NewRelic.notice_error(exception, __STACKTRACE__)
end
```
"""
@spec notice_error(Exception.t(), Exception.stacktrace()) :: :ok
defdelegate notice_error(exception, stacktrace), to: NewRelic.Transaction.Reporter

@doc false
defdelegate enable_erlang_trace, to: NewRelic.Transaction.ErlangTraceManager

Expand Down
8 changes: 8 additions & 0 deletions lib/new_relic/transaction/reporter.ex
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,14 @@ defmodule NewRelic.Transaction.Reporter do
:ok
end

def notice_error(exception, stacktrace) do
if NewRelic.Config.feature?(:error_collector) do
error(%{kind: :error, reason: exception, stack: stacktrace})
end

:ok
end

def error(error) do
Transaction.Sidecar.add(transaction_error: {:error, error})
end
Expand Down
26 changes: 26 additions & 0 deletions test/other_transaction_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -246,4 +246,30 @@ defmodule OtherTransactionTest do

refute spansaction.attributes[:error]
end

test "Report a raise that is rescued inside a Transaction" do
TestHelper.restart_harvest_cycle(Collector.TransactionErrorEvent.HarvestCycle)

{:ok, pid} =
Task.start(fn ->
NewRelic.start_transaction("TestTransaction", "Rescued")

try do
raise RuntimeError, "RESCUED"
rescue
exception ->
NewRelic.notice_error(exception, __STACKTRACE__)
:move_on
end
end)

Process.monitor(pid)
assert_receive {:DOWN, _ref, :process, ^pid, _reason}, 1_000

events = TestHelper.gather_harvest(Collector.TransactionErrorEvent.Harvester)

assert Enum.find(events, fn [intrinsic, _, _] ->
intrinsic[:"error.message"] =~ "RESCUED"
end)
end
end
Loading