Skip to content

Commit 5fffd1b

Browse files
authored
feat(nestjs): Add SentryGlobalGenericFilter and allow specifying application ref in global filter (#13673)
1 parent 40ebfad commit 5fffd1b

File tree

17 files changed

+414
-2
lines changed

17 files changed

+414
-2
lines changed

.github/workflows/build.yml

+1
Original file line numberDiff line numberDiff line change
@@ -923,6 +923,7 @@ jobs:
923923
'nestjs-distributed-tracing',
924924
'nestjs-with-submodules',
925925
'nestjs-with-submodules-decorator',
926+
'nestjs-basic-with-graphql',
926927
'nestjs-graphql',
927928
'node-exports-test-app',
928929
'node-koa',
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# compiled output
2+
/dist
3+
/node_modules
4+
/build
5+
6+
# Logs
7+
logs
8+
*.log
9+
npm-debug.log*
10+
pnpm-debug.log*
11+
yarn-debug.log*
12+
yarn-error.log*
13+
lerna-debug.log*
14+
15+
# OS
16+
.DS_Store
17+
18+
# Tests
19+
/coverage
20+
/.nyc_output
21+
22+
# IDEs and editors
23+
/.idea
24+
.project
25+
.classpath
26+
.c9/
27+
*.launch
28+
.settings/
29+
*.sublime-workspace
30+
31+
# IDE - VSCode
32+
.vscode/*
33+
!.vscode/settings.json
34+
!.vscode/tasks.json
35+
!.vscode/launch.json
36+
!.vscode/extensions.json
37+
38+
# dotenv environment variable files
39+
.env
40+
.env.development.local
41+
.env.test.local
42+
.env.production.local
43+
.env.local
44+
45+
# temp directory
46+
.temp
47+
.tmp
48+
49+
# Runtime data
50+
pids
51+
*.pid
52+
*.seed
53+
*.pid.lock
54+
55+
# Diagnostic reports (https://nodejs.org/api/report.html)
56+
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
@sentry:registry=http://127.0.0.1:4873
2+
@sentry-internal:registry=http://127.0.0.1:4873
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"$schema": "https://json.schemastore.org/nest-cli",
3+
"collection": "@nestjs/schematics",
4+
"sourceRoot": "src",
5+
"compilerOptions": {
6+
"deleteOutDir": true
7+
}
8+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
{
2+
"name": "nestjs-basic-with-graphql",
3+
"version": "0.0.1",
4+
"private": true,
5+
"scripts": {
6+
"build": "nest build",
7+
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
8+
"start": "nest start",
9+
"start:dev": "nest start --watch",
10+
"start:debug": "nest start --debug --watch",
11+
"start:prod": "node dist/main",
12+
"clean": "npx rimraf node_modules pnpm-lock.yaml",
13+
"test": "playwright test",
14+
"test:build": "pnpm install",
15+
"test:assert": "pnpm test"
16+
},
17+
"dependencies": {
18+
"@apollo/server": "^4.10.4",
19+
"@nestjs/apollo": "^12.2.0",
20+
"@nestjs/common": "^10.3.10",
21+
"@nestjs/core": "^10.3.10",
22+
"@nestjs/graphql": "^12.2.0",
23+
"@nestjs/platform-express": "^10.3.10",
24+
"@sentry/nestjs": "^8.21.0",
25+
"graphql": "^16.9.0",
26+
"reflect-metadata": "^0.1.13",
27+
"rxjs": "^7.8.1"
28+
},
29+
"devDependencies": {
30+
"@playwright/test": "^1.44.1",
31+
"@sentry-internal/test-utils": "link:../../../test-utils",
32+
"@nestjs/cli": "^10.0.0",
33+
"@nestjs/schematics": "^10.0.0",
34+
"@nestjs/testing": "^10.0.0",
35+
"@types/express": "^4.17.17",
36+
"@types/node": "18.15.1",
37+
"@types/supertest": "^6.0.0",
38+
"@typescript-eslint/eslint-plugin": "^6.0.0",
39+
"@typescript-eslint/parser": "^6.0.0",
40+
"eslint": "^8.42.0",
41+
"eslint-config-prettier": "^9.0.0",
42+
"eslint-plugin-prettier": "^5.0.0",
43+
"prettier": "^3.0.0",
44+
"source-map-support": "^0.5.21",
45+
"supertest": "^6.3.3",
46+
"ts-loader": "^9.4.3",
47+
"tsconfig-paths": "^4.2.0",
48+
"typescript": "^4.9.5"
49+
}
50+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import { getPlaywrightConfig } from '@sentry-internal/test-utils';
2+
3+
const config = getPlaywrightConfig({
4+
startCommand: `pnpm start`,
5+
});
6+
7+
export default config;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { Controller, Get, Param } from '@nestjs/common';
2+
import { AppService } from './app.service';
3+
4+
@Controller()
5+
export class AppController {
6+
constructor(private readonly appService: AppService) {}
7+
8+
@Get('test-exception/:id')
9+
async testException(@Param('id') id: string) {
10+
return this.appService.testException(id);
11+
}
12+
13+
@Get('test-expected-400-exception/:id')
14+
async testExpected400Exception(@Param('id') id: string) {
15+
return this.appService.testExpected400Exception(id);
16+
}
17+
18+
@Get('test-expected-500-exception/:id')
19+
async testExpected500Exception(@Param('id') id: string) {
20+
return this.appService.testExpected500Exception(id);
21+
}
22+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { ApolloDriver } from '@nestjs/apollo';
2+
import { Logger, Module } from '@nestjs/common';
3+
import { GraphQLModule } from '@nestjs/graphql';
4+
import { SentryModule } from '@sentry/nestjs/setup';
5+
import { AppController } from './app.controller';
6+
import { AppResolver } from './app.resolver';
7+
import { AppService } from './app.service';
8+
9+
@Module({
10+
imports: [
11+
SentryModule.forRoot(),
12+
GraphQLModule.forRoot({
13+
driver: ApolloDriver,
14+
autoSchemaFile: true,
15+
playground: true, // sets up a playground on https://localhost:3000/graphql
16+
}),
17+
],
18+
controllers: [AppController],
19+
providers: [
20+
AppService,
21+
AppResolver,
22+
{
23+
provide: Logger,
24+
useClass: Logger,
25+
},
26+
],
27+
})
28+
export class AppModule {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { Query, Resolver } from '@nestjs/graphql';
2+
3+
@Resolver()
4+
export class AppResolver {
5+
@Query(() => String)
6+
test(): string {
7+
return 'Test endpoint!';
8+
}
9+
10+
@Query(() => String)
11+
error(): string {
12+
throw new Error('This is an exception!');
13+
}
14+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
2+
3+
@Injectable()
4+
export class AppService {
5+
testException(id: string) {
6+
throw new Error(`This is an exception with id ${id}`);
7+
}
8+
9+
testExpected400Exception(id: string) {
10+
throw new HttpException(`This is an expected 400 exception with id ${id}`, HttpStatus.BAD_REQUEST);
11+
}
12+
13+
testExpected500Exception(id: string) {
14+
throw new HttpException(`This is an expected 500 exception with id ${id}`, HttpStatus.INTERNAL_SERVER_ERROR);
15+
}
16+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import * as Sentry from '@sentry/nestjs';
2+
3+
Sentry.init({
4+
environment: 'qa', // dynamic sampling bias to keep transactions
5+
dsn: process.env.E2E_TEST_DSN,
6+
tunnel: `http://localhost:3031/`, // proxy server
7+
tracesSampleRate: 1,
8+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// Import this first
2+
import './instrument';
3+
4+
// Import other modules
5+
import { HttpAdapterHost, NestFactory } from '@nestjs/core';
6+
import { SentryGlobalGenericFilter } from '@sentry/nestjs/setup';
7+
import { AppModule } from './app.module';
8+
9+
const PORT = 3030;
10+
11+
async function bootstrap() {
12+
const app = await NestFactory.create(AppModule);
13+
14+
const { httpAdapter } = app.get(HttpAdapterHost);
15+
app.useGlobalFilters(new SentryGlobalGenericFilter(httpAdapter as any));
16+
17+
await app.listen(PORT);
18+
}
19+
20+
bootstrap();
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import { startEventProxyServer } from '@sentry-internal/test-utils';
2+
3+
startEventProxyServer({
4+
port: 3031,
5+
proxyServerName: 'nestjs-basic-with-graphql',
6+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
import { expect, test } from '@playwright/test';
2+
import { waitForError, waitForTransaction } from '@sentry-internal/test-utils';
3+
4+
test('Sends exception to Sentry', async ({ baseURL }) => {
5+
const errorEventPromise = waitForError('nestjs-basic-with-graphql', event => {
6+
return !event.type && event.exception?.values?.[0]?.value === 'This is an exception with id 123';
7+
});
8+
9+
const response = await fetch(`${baseURL}/test-exception/123`);
10+
expect(response.status).toBe(500);
11+
12+
const errorEvent = await errorEventPromise;
13+
14+
expect(errorEvent.exception?.values).toHaveLength(1);
15+
expect(errorEvent.exception?.values?.[0]?.value).toBe('This is an exception with id 123');
16+
17+
expect(errorEvent.request).toEqual({
18+
method: 'GET',
19+
cookies: {},
20+
headers: expect.any(Object),
21+
url: 'http://localhost:3030/test-exception/123',
22+
});
23+
24+
expect(errorEvent.transaction).toEqual('GET /test-exception/:id');
25+
26+
expect(errorEvent.contexts?.trace).toEqual({
27+
trace_id: expect.any(String),
28+
span_id: expect.any(String),
29+
});
30+
});
31+
32+
test('Does not send HttpExceptions to Sentry', async ({ baseURL }) => {
33+
let errorEventOccurred = false;
34+
35+
waitForError('nestjs-basic-with-graphql', event => {
36+
if (!event.type && event.exception?.values?.[0]?.value === 'This is an expected 400 exception with id 123') {
37+
errorEventOccurred = true;
38+
}
39+
40+
return event?.transaction === 'GET /test-expected-400-exception/:id';
41+
});
42+
43+
waitForError('nestjs-basic-with-graphql', event => {
44+
if (!event.type && event.exception?.values?.[0]?.value === 'This is an expected 500 exception with id 123') {
45+
errorEventOccurred = true;
46+
}
47+
48+
return event?.transaction === 'GET /test-expected-500-exception/:id';
49+
});
50+
51+
const transactionEventPromise400 = waitForTransaction('nestjs-basic-with-graphql', transactionEvent => {
52+
return transactionEvent?.transaction === 'GET /test-expected-400-exception/:id';
53+
});
54+
55+
const transactionEventPromise500 = waitForTransaction('nestjs-basic-with-graphql', transactionEvent => {
56+
return transactionEvent?.transaction === 'GET /test-expected-500-exception/:id';
57+
});
58+
59+
const response400 = await fetch(`${baseURL}/test-expected-400-exception/123`);
60+
expect(response400.status).toBe(400);
61+
62+
const response500 = await fetch(`${baseURL}/test-expected-500-exception/123`);
63+
expect(response500.status).toBe(500);
64+
65+
await transactionEventPromise400;
66+
await transactionEventPromise500;
67+
68+
(await fetch(`${baseURL}/flush`)).text();
69+
70+
expect(errorEventOccurred).toBe(false);
71+
});
72+
73+
test('Sends graphql exception to Sentry', async ({ baseURL }) => {
74+
const errorEventPromise = waitForError('nestjs-basic-with-graphql', event => {
75+
return !event.type && event.exception?.values?.[0]?.value === 'This is an exception!';
76+
});
77+
78+
const response = await fetch(`${baseURL}/graphql`, {
79+
method: 'POST',
80+
headers: {
81+
'Content-Type': 'application/json',
82+
},
83+
body: JSON.stringify({
84+
query: `query { error }`,
85+
}),
86+
});
87+
88+
const json_response = await response.json();
89+
const errorEvent = await errorEventPromise;
90+
91+
expect(json_response?.errors[0]).toEqual({
92+
message: 'This is an exception!',
93+
locations: expect.any(Array),
94+
path: ['error'],
95+
extensions: {
96+
code: 'INTERNAL_SERVER_ERROR',
97+
stacktrace: expect.any(Array),
98+
},
99+
});
100+
101+
expect(errorEvent.exception?.values).toHaveLength(1);
102+
expect(errorEvent.exception?.values?.[0]?.value).toBe('This is an exception!');
103+
104+
expect(errorEvent.request).toEqual({
105+
method: 'POST',
106+
cookies: {},
107+
data: '{"query":"query { error }"}',
108+
headers: expect.any(Object),
109+
url: 'http://localhost:3030/graphql',
110+
});
111+
112+
expect(errorEvent.transaction).toEqual('POST /graphql');
113+
114+
expect(errorEvent.contexts?.trace).toEqual({
115+
trace_id: expect.any(String),
116+
span_id: expect.any(String),
117+
});
118+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"extends": "./tsconfig.json",
3+
"exclude": ["node_modules", "test", "dist"]
4+
}

0 commit comments

Comments
 (0)