Skip to content

Commit 03fa4f5

Browse files
committed
Make sure newrelic_end_transaction is called even if things go run (thanks gpt-5.6-terra default)
1 parent b231a2d commit 03fa4f5

2 files changed

Lines changed: 42 additions & 3 deletions

File tree

‎src/Adapter/NewRelicOnMessageAdapter.php‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,10 @@ public function __invoke(WorkermanTcpConnection $workermanTcpConnection, Workerm
1616
{
1717
newrelic_start_transaction($this->appname);
1818

19-
$this->onRequest->__invoke($workermanTcpConnection, $workermanRequest);
20-
21-
newrelic_end_transaction();
19+
try {
20+
$this->onRequest->__invoke($workermanTcpConnection, $workermanRequest);
21+
} finally {
22+
newrelic_end_transaction();
23+
}
2224
}
2325
}

‎tests/Unit/Adapter/NewRelicOnMessageAdapterTest.php‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,5 +110,42 @@ public function testInvoke(): void
110110
self::assertSame([['appname' => 'myapp', 'license' => null]], TestNewRelicStartTransaction::all());
111111
self::assertSame([['ignore' => false]], TestNewRelicEndTransaction::all());
112112
}
113+
114+
public function testInvokeEndsTransactionWhenRequestHandlingFails(): void
115+
{
116+
TestNewRelicStartTransaction::reset();
117+
TestNewRelicEndTransaction::reset();
118+
119+
$builder = new MockObjectBuilder();
120+
121+
/** @var WorkermanTcpConnection $workermanTcpConnection */
122+
$workermanTcpConnection = $builder->create(WorkermanTcpConnection::class, []);
123+
124+
/** @var WorkermanRequest $workermanRequest */
125+
$workermanRequest = $builder->create(WorkermanRequest::class, []);
126+
127+
$exception = new \RuntimeException('Request handling failed');
128+
129+
$onMessage = new class($exception) implements OnMessageInterface {
130+
public function __construct(private readonly \RuntimeException $exception) {}
131+
132+
public function __invoke(WorkermanTcpConnection $workermanTcpConnection, WorkermanRequest $workermanRequest): void
133+
{
134+
throw $this->exception;
135+
}
136+
};
137+
138+
$adapter = new NewRelicOnMessageAdapter($onMessage, 'myapp');
139+
140+
try {
141+
$adapter($workermanTcpConnection, $workermanRequest);
142+
self::fail('Expected the request handler exception to be rethrown.');
143+
} catch (\RuntimeException $caughtException) {
144+
self::assertSame($exception, $caughtException);
145+
}
146+
147+
self::assertSame([['appname' => 'myapp', 'license' => null]], TestNewRelicStartTransaction::all());
148+
self::assertSame([['ignore' => false]], TestNewRelicEndTransaction::all());
149+
}
113150
}
114151
}

0 commit comments

Comments
 (0)