Skip to content

Commit

Permalink
[frontend] fix http.status_code on error (#810)
Browse files Browse the repository at this point in the history
* fix http.status_code on error

Signed-off-by: Pierre Tessier <pierre@pierretessier.com>

* only end span when synthetic

Signed-off-by: Pierre Tessier <pierre@pierretessier.com>

* fix http.status_code on error

Signed-off-by: Pierre Tessier <pierre@pierretessier.com>

---------

Signed-off-by: Pierre Tessier <pierre@pierretessier.com>
  • Loading branch information
puckpuck authored Mar 30, 2023
1 parent 37a2a25 commit 954d35a
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 12 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ release.
([#799](https://github.com/open-telemetry/opentelemetry-demo/pull/799))
* Update frontend JavaScript SDKs to: 1.10.1/0.36.x
([#805](https://github.com/open-telemetry/opentelemetry-demo/pull/805))
* Fix http.status_code on error in frontend
([#810](https://github.com/open-telemetry/opentelemetry-demo/pull/810))

## v0.1.0

Expand Down
21 changes: 9 additions & 12 deletions src/frontend/utils/telemetry/InstrumentationMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ const InstrumentationMiddleware = (handler: NextApiHandler): NextApiHandler => {
attributes: {
'app.synthetic_request': true,
[SemanticAttributes.HTTP_TARGET]: target,
[SemanticAttributes.HTTP_STATUS_CODE]: response.statusCode,
[SemanticAttributes.HTTP_METHOD]: method,
[SemanticAttributes.HTTP_USER_AGENT]: headers['user-agent'] || '',
[SemanticAttributes.HTTP_URL]: `${headers.host}${url}`,
Expand All @@ -56,30 +55,28 @@ const InstrumentationMiddleware = (handler: NextApiHandler): NextApiHandler => {
span.setAttribute(AttributeNames.SESSION_ID, request.query['sessionId']);
}

let httpStatus = 200;
try {
await runWithSpan(span, async () => handler(request, response));
httpStatus = response.statusCode;
} catch (error) {
span.recordException(error as Exception);
span.setStatus({ code: SpanStatusCode.ERROR });
httpStatus = 500;
throw error;
} finally {
requestCounter.add(1, { method, target, status: response.statusCode });
span.end();
requestCounter.add(1, { method, target, status: httpStatus });
span.setAttribute(SemanticAttributes.HTTP_STATUS_CODE, httpStatus);
if (baggage?.getEntry('synthetic_request')?.value == 'true') {
span.end();
}
}
};
};

async function runWithSpan(parentSpan: Span, fn: () => Promise<unknown>) {
const ctx = trace.setSpan(context.active(), parentSpan);

try {
return await context.with(ctx, fn);
} catch (error) {
parentSpan.recordException(error as Exception);
parentSpan.setStatus({ code: SpanStatusCode.ERROR });

throw error;
}
return await context.with(ctx, fn);
}

export default InstrumentationMiddleware;

0 comments on commit 954d35a

Please sign in to comment.