Skip to content

Commit

Permalink
Merge pull request #470 from newrelic/vince/notice-exception
Browse files Browse the repository at this point in the history
Add notice_error function for rescued exceptions
  • Loading branch information
tpitale authored Jan 7, 2025
2 parents dae6d10 + a4ac4f2 commit 94bf26c
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
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

0 comments on commit 94bf26c

Please sign in to comment.