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

chore(nestjs): Move setupNestErrorHandler method from @sentry/node to @sentry/nestjs #12829

Closed
wants to merge 4 commits into from
Closed
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
1 change: 1 addition & 0 deletions dev-packages/node-integration-tests/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"@prisma/client": "5.9.1",
"@sentry/node": "8.15.0",
"@sentry/types": "8.15.0",
"@sentry/nestjs": "8.15.0",
"@types/mongodb": "^3.6.20",
"@types/mysql": "^2.15.21",
"@types/pg": "^8.6.5",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
/* eslint-disable @typescript-eslint/naming-convention */
/* eslint-disable @typescript-eslint/explicit-member-accessibility */
import { loggingTransport, sendPortToRunner } from '@sentry-internal/node-integration-tests';
import * as Sentry from '@sentry/node';
import * as Sentry from '@sentry/nestjs';

Sentry.init({
dsn: 'https://[email protected]/1337',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
/* eslint-disable @typescript-eslint/naming-convention */
/* eslint-disable @typescript-eslint/explicit-member-accessibility */
import { loggingTransport, sendPortToRunner } from '@sentry-internal/node-integration-tests';
import * as Sentry from '@sentry/node';
import * as Sentry from '@sentry/nestjs';

Sentry.init({
dsn: 'https://[email protected]/1337',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
/* eslint-disable @typescript-eslint/naming-convention */
/* eslint-disable @typescript-eslint/explicit-member-accessibility */
import { loggingTransport, sendPortToRunner } from '@sentry-internal/node-integration-tests';
import * as Sentry from '@sentry/node';
import * as Sentry from '@sentry/nestjs';

Sentry.init({
dsn: 'https://[email protected]/1337',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
/* eslint-disable @typescript-eslint/naming-convention */
/* eslint-disable @typescript-eslint/explicit-member-accessibility */
import { loggingTransport, sendPortToRunner } from '@sentry-internal/node-integration-tests';
import * as Sentry from '@sentry/node';
import * as Sentry from '@sentry/nestjs';

Sentry.init({
dsn: 'https://[email protected]/1337',
Expand Down
1 change: 0 additions & 1 deletion packages/astro/src/index.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,6 @@ export {
setupExpressErrorHandler,
setupHapiErrorHandler,
setupKoaErrorHandler,
setupNestErrorHandler,
setUser,
spanToBaggageHeader,
spanToJSON,
Expand Down
1 change: 0 additions & 1 deletion packages/aws-serverless/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,6 @@ export {
mysql2Integration,
redisIntegration,
nestIntegration,
setupNestErrorHandler,
postgresIntegration,
prismaIntegration,
hapiIntegration,
Expand Down
1 change: 0 additions & 1 deletion packages/bun/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,6 @@ export {
mysql2Integration,
redisIntegration,
nestIntegration,
setupNestErrorHandler,
postgresIntegration,
prismaIntegration,
hapiIntegration,
Expand Down
1 change: 0 additions & 1 deletion packages/google-cloud-serverless/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,6 @@ export {
mysql2Integration,
redisIntegration,
nestIntegration,
setupNestErrorHandler,
postgresIntegration,
prismaIntegration,
hapiIntegration,
Expand Down
1 change: 1 addition & 0 deletions packages/nestjs/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export * from '@sentry/node';

export { setupNestErrorHandler } from './setup';
export { init } from './sdk';

export { SentryTraced } from './span-decorator';
Expand Down
113 changes: 113 additions & 0 deletions packages/nestjs/src/setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import {
SEMANTIC_ATTRIBUTE_SENTRY_OP,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
captureException,
getClient,
getDefaultIsolationScope,
getIsolationScope,
spanToJSON,
} from '@sentry/core';
import type { Span } from '@sentry/types';
import { logger } from '@sentry/utils';

interface MinimalNestJsExecutionContext {
getType: () => string;

switchToHttp: () => {
// minimal request object
// according to official types, all properties are required but
// let's play it safe and assume they're optional
getRequest: () => {
route?: {
path?: string;
};
method?: string;
};
};
}

interface NestJsErrorFilter {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
catch(exception: any, host: any): void;
}

interface MinimalNestJsApp {
useGlobalFilters: (arg0: NestJsErrorFilter) => void;
useGlobalInterceptors: (interceptor: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
intercept: (context: MinimalNestJsExecutionContext, next: { handle: () => any }) => any;
}) => void;
}

/**
* Setup an error handler for Nest.
*/
export function setupNestErrorHandler(app: MinimalNestJsApp, baseFilter: NestJsErrorFilter): void {
// Sadly, NestInstrumentation has no requestHook, so we need to add the attributes here
// We register this hook in this method, because if we register it in the integration `setup`,
// it would always run even for users that are not even using Nest.js
const client = getClient();
if (client) {
client.on('spanStart', span => {
addNestSpanAttributes(span);
});
}

app.useGlobalInterceptors({
intercept(context, next) {
if (getIsolationScope() === getDefaultIsolationScope()) {
logger.warn('Isolation scope is still the default isolation scope, skipping setting transactionName.');
return next.handle();
}

if (context.getType() === 'http') {
const req = context.switchToHttp().getRequest();
if (req.route) {
getIsolationScope().setTransactionName(`${req.method?.toUpperCase() || 'GET'} ${req.route.path}`);
}
}

return next.handle();
},
});

const wrappedFilter = new Proxy(baseFilter, {
get(target, prop, receiver) {
if (prop === 'catch') {
const originalCatch = Reflect.get(target, prop, receiver);

return (exception: unknown, host: unknown) => {
const status_code = (exception as { status?: number }).status;

// don't report expected errors
if (status_code !== undefined && status_code >= 400 && status_code < 500) {
return originalCatch.apply(target, [exception, host]);
}

captureException(exception);
return originalCatch.apply(target, [exception, host]);
};
}
return Reflect.get(target, prop, receiver);
},
});

app.useGlobalFilters(wrappedFilter);
}

function addNestSpanAttributes(span: Span): void {
const attributes = spanToJSON(span).data || {};

// this is one of: app_creation, request_context, handler
const type = attributes['nestjs.type'];

// If this is already set, or we have no nest.js span, no need to process again...
if (attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] || !type) {
return;
}

span.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.otel.nestjs',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: `${type}.nestjs`,
});
}
2 changes: 1 addition & 1 deletion packages/node/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export { mongooseIntegration } from './integrations/tracing/mongoose';
export { mysqlIntegration } from './integrations/tracing/mysql';
export { mysql2Integration } from './integrations/tracing/mysql2';
export { redisIntegration } from './integrations/tracing/redis';
export { nestIntegration, setupNestErrorHandler } from './integrations/tracing/nest';
export { nestIntegration } from './integrations/tracing/nest';
export { postgresIntegration } from './integrations/tracing/postgres';
export { prismaIntegration } from './integrations/tracing/prisma';
export { hapiIntegration, setupHapiErrorHandler } from './integrations/tracing/hapi';
Expand Down
116 changes: 2 additions & 114 deletions packages/node/src/integrations/tracing/nest.ts
Original file line number Diff line number Diff line change
@@ -1,47 +1,8 @@
import { NestInstrumentation } from '@opentelemetry/instrumentation-nestjs-core';
import {
SEMANTIC_ATTRIBUTE_SENTRY_OP,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
captureException,
defineIntegration,
getClient,
getDefaultIsolationScope,
getIsolationScope,
spanToJSON,
} from '@sentry/core';
import type { IntegrationFn, Span } from '@sentry/types';
import { logger } from '@sentry/utils';
import { defineIntegration } from '@sentry/core';
import type { IntegrationFn } from '@sentry/types';
import { generateInstrumentOnce } from '../../otel/instrument';

interface MinimalNestJsExecutionContext {
getType: () => string;

switchToHttp: () => {
// minimal request object
// according to official types, all properties are required but
// let's play it safe and assume they're optional
getRequest: () => {
route?: {
path?: string;
};
method?: string;
};
};
}

interface NestJsErrorFilter {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
catch(exception: any, host: any): void;
}

interface MinimalNestJsApp {
useGlobalFilters: (arg0: NestJsErrorFilter) => void;
useGlobalInterceptors: (interceptor: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
intercept: (context: MinimalNestJsExecutionContext, next: { handle: () => any }) => any;
}) => void;
}

const INTEGRATION_NAME = 'Nest';

export const instrumentNest = generateInstrumentOnce(INTEGRATION_NAME, () => new NestInstrumentation());
Expand All @@ -61,76 +22,3 @@ const _nestIntegration = (() => {
* Capture tracing data for nest.
*/
export const nestIntegration = defineIntegration(_nestIntegration);

/**
* Setup an error handler for Nest.
*/
export function setupNestErrorHandler(app: MinimalNestJsApp, baseFilter: NestJsErrorFilter): void {
// Sadly, NestInstrumentation has no requestHook, so we need to add the attributes here
// We register this hook in this method, because if we register it in the integration `setup`,
// it would always run even for users that are not even using Nest.js
const client = getClient();
if (client) {
client.on('spanStart', span => {
addNestSpanAttributes(span);
});
}

app.useGlobalInterceptors({
intercept(context, next) {
if (getIsolationScope() === getDefaultIsolationScope()) {
logger.warn('Isolation scope is still the default isolation scope, skipping setting transactionName.');
return next.handle();
}

if (context.getType() === 'http') {
const req = context.switchToHttp().getRequest();
if (req.route) {
getIsolationScope().setTransactionName(`${req.method?.toUpperCase() || 'GET'} ${req.route.path}`);
}
}

return next.handle();
},
});

const wrappedFilter = new Proxy(baseFilter, {
get(target, prop, receiver) {
if (prop === 'catch') {
const originalCatch = Reflect.get(target, prop, receiver);

return (exception: unknown, host: unknown) => {
const status_code = (exception as { status?: number }).status;

// don't report expected errors
if (status_code !== undefined && status_code >= 400 && status_code < 500) {
return originalCatch.apply(target, [exception, host]);
}

captureException(exception);
return originalCatch.apply(target, [exception, host]);
};
}
return Reflect.get(target, prop, receiver);
},
});

app.useGlobalFilters(wrappedFilter);
}

function addNestSpanAttributes(span: Span): void {
const attributes = spanToJSON(span).data || {};

// this is one of: app_creation, request_context, handler
const type = attributes['nestjs.type'];

// If this is already set, or we have no nest.js span, no need to process again...
if (attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] || !type) {
return;
}

span.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.otel.nestjs',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: `${type}.nestjs`,
});
}
1 change: 0 additions & 1 deletion packages/remix/src/index.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,6 @@ export {
setupExpressErrorHandler,
setupHapiErrorHandler,
setupKoaErrorHandler,
setupNestErrorHandler,
setUser,
spanToBaggageHeader,
spanToJSON,
Expand Down
1 change: 0 additions & 1 deletion packages/solidstart/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,6 @@ export {
setupExpressErrorHandler,
setupHapiErrorHandler,
setupKoaErrorHandler,
setupNestErrorHandler,
setUser,
spanToBaggageHeader,
spanToJSON,
Expand Down
1 change: 0 additions & 1 deletion packages/sveltekit/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,6 @@ export {
setupExpressErrorHandler,
setupHapiErrorHandler,
setupKoaErrorHandler,
setupNestErrorHandler,
setUser,
spanToBaggageHeader,
spanToJSON,
Expand Down
Loading