Skip to content

Commit 86aeba8

Browse files
authored
feat(nestjs): Add SentryGlobalGraphQLFilter (#13545)
`BaseExceptionFilter` should not be used in GraphQL applications ([ref](nestjs/nest#5958 (comment))). Currently the `SentryGlobalFilter` extends the `BaseExceptionFilter`, which is why GraphQL applications break if an exception is thrown. By default, NestJS + GraphQL environments use the `ExternalExceptionFilter` ([ref](https://github.com/nestjs/nest/blob/master/packages/core/exceptions/external-exception-filter.ts)), which essentially just rethrows the error. So adding a new `SentryGlobalGraphQLFilter` that captures the exception in Sentry and then simply rethrows the error. Additionally, added a new e2e test app to test GraphQL applications. Added a test to verify that basic error reporting works correctly now.
1 parent 15fcfea commit 86aeba8

File tree

15 files changed

+325
-4
lines changed

15 files changed

+325
-4
lines changed

.github/workflows/build.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -908,6 +908,7 @@ jobs:
908908
'nestjs-basic',
909909
'nestjs-distributed-tracing',
910910
'nestjs-with-submodules',
911+
'nestjs-graphql',
911912
'node-exports-test-app',
912913
'node-koa',
913914
'node-connect',
Lines changed: 56 additions & 0 deletions
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
Lines changed: 2 additions & 0 deletions
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
Lines changed: 8 additions & 0 deletions
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+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
{
2+
"name": "nestjs-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+
}
Lines changed: 7 additions & 0 deletions
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;
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { ApolloDriver } from '@nestjs/apollo';
2+
import { Logger, Module } from '@nestjs/common';
3+
import { APP_FILTER } from '@nestjs/core';
4+
import { GraphQLModule } from '@nestjs/graphql';
5+
import { SentryGlobalGraphQLFilter, SentryModule } from '@sentry/nestjs/setup';
6+
import { AppResolver } from './app.resolver';
7+
8+
@Module({
9+
imports: [
10+
SentryModule.forRoot(),
11+
GraphQLModule.forRoot({
12+
driver: ApolloDriver,
13+
autoSchemaFile: true,
14+
playground: true, // sets up a playground on https://localhost:3000/graphql
15+
}),
16+
],
17+
controllers: [],
18+
providers: [
19+
AppResolver,
20+
{
21+
provide: APP_FILTER,
22+
useClass: SentryGlobalGraphQLFilter,
23+
},
24+
{
25+
provide: Logger,
26+
useClass: Logger,
27+
},
28+
],
29+
})
30+
export class AppModule {}
Lines changed: 14 additions & 0 deletions
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+
}
Lines changed: 8 additions & 0 deletions
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+
});
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Import this first
2+
import './instrument';
3+
4+
// Import other modules
5+
import { NestFactory } from '@nestjs/core';
6+
import { AppModule } from './app.module';
7+
8+
const PORT = 3030;
9+
10+
async function bootstrap() {
11+
const app = await NestFactory.create(AppModule);
12+
await app.listen(PORT);
13+
}
14+
15+
bootstrap();
Lines changed: 6 additions & 0 deletions
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-graphql',
6+
});
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import { expect, test } from '@playwright/test';
2+
import { waitForError } from '@sentry-internal/test-utils';
3+
4+
test('Sends exception to Sentry', async ({ baseURL }) => {
5+
const errorEventPromise = waitForError('nestjs-graphql', event => {
6+
return !event.type && event.exception?.values?.[0]?.value === 'This is an exception!';
7+
});
8+
9+
const response = await fetch(`${baseURL}/graphql`, {
10+
method: 'POST',
11+
headers: {
12+
'Content-Type': 'application/json',
13+
},
14+
body: JSON.stringify({
15+
query: `query { error }`,
16+
}),
17+
});
18+
19+
const json_response = await response.json();
20+
const errorEvent = await errorEventPromise;
21+
22+
expect(json_response?.errors[0]).toEqual({
23+
message: 'This is an exception!',
24+
locations: expect.any(Array),
25+
path: ['error'],
26+
extensions: {
27+
code: 'INTERNAL_SERVER_ERROR',
28+
stacktrace: expect.any(Array),
29+
},
30+
});
31+
32+
expect(errorEvent.exception?.values).toHaveLength(1);
33+
expect(errorEvent.exception?.values?.[0]?.value).toBe('This is an exception!');
34+
35+
expect(errorEvent.request).toEqual({
36+
method: 'POST',
37+
cookies: {},
38+
data: '{"query":"query { error }"}',
39+
headers: expect.any(Object),
40+
url: 'http://localhost:3030/graphql',
41+
});
42+
43+
expect(errorEvent.transaction).toEqual('POST /graphql');
44+
45+
expect(errorEvent.contexts?.trace).toEqual({
46+
trace_id: expect.any(String),
47+
span_id: expect.any(String),
48+
});
49+
});
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"extends": "./tsconfig.json",
3+
"exclude": ["node_modules", "test", "dist"]
4+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{
2+
"compilerOptions": {
3+
"module": "commonjs",
4+
"declaration": true,
5+
"removeComments": true,
6+
"emitDecoratorMetadata": true,
7+
"experimentalDecorators": true,
8+
"allowSyntheticDefaultImports": true,
9+
"target": "ES2021",
10+
"sourceMap": true,
11+
"outDir": "./dist",
12+
"baseUrl": "./",
13+
"incremental": true,
14+
"skipLibCheck": true,
15+
"strictNullChecks": false,
16+
"noImplicitAny": false,
17+
"strictBindCallApply": false,
18+
"forceConsistentCasingInFileNames": false,
19+
"noFallthroughCasesInSwitch": false,
20+
"moduleResolution": "Node16"
21+
}
22+
}

packages/nestjs/src/setup.ts

Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import type {
66
NestInterceptor,
77
OnModuleInit,
88
} from '@nestjs/common';
9-
import { Catch, Global, Injectable, Module } from '@nestjs/common';
9+
import { Catch, Global, HttpException, Injectable, Logger, Module } from '@nestjs/common';
1010
import { APP_INTERCEPTOR, BaseExceptionFilter } from '@nestjs/core';
1111
import {
1212
SEMANTIC_ATTRIBUTE_SENTRY_OP,
@@ -31,7 +31,11 @@ import { isExpectedError } from './helpers';
3131
*/
3232
class SentryTracingInterceptor implements NestInterceptor {
3333
// used to exclude this class from being auto-instrumented
34-
public static readonly __SENTRY_INTERNAL__ = true;
34+
public readonly __SENTRY_INTERNAL__: boolean;
35+
36+
public constructor() {
37+
this.__SENTRY_INTERNAL__ = true;
38+
}
3539

3640
/**
3741
* Intercepts HTTP requests to set the transaction name for Sentry tracing.
@@ -61,7 +65,12 @@ export { SentryTracingInterceptor };
6165
* Global filter to handle exceptions and report them to Sentry.
6266
*/
6367
class SentryGlobalFilter extends BaseExceptionFilter {
64-
public static readonly __SENTRY_INTERNAL__ = true;
68+
public readonly __SENTRY_INTERNAL__: boolean;
69+
70+
public constructor() {
71+
super();
72+
this.__SENTRY_INTERNAL__ = true;
73+
}
6574

6675
/**
6776
* Catches exceptions and reports them to Sentry unless they are expected errors.
@@ -78,11 +87,51 @@ class SentryGlobalFilter extends BaseExceptionFilter {
7887
Catch()(SentryGlobalFilter);
7988
export { SentryGlobalFilter };
8089

90+
/**
91+
* Global filter to handle exceptions and report them to Sentry.
92+
*
93+
* The BaseExceptionFilter does not work well in GraphQL applications.
94+
* By default, Nest GraphQL applications use the ExternalExceptionFilter, which just rethrows the error:
95+
* https://github.com/nestjs/nest/blob/master/packages/core/exceptions/external-exception-filter.ts
96+
*
97+
* The ExternalExceptinFilter is not exported, so we reimplement this filter here.
98+
*/
99+
class SentryGlobalGraphQLFilter {
100+
private static readonly _logger = new Logger('ExceptionsHandler');
101+
public readonly __SENTRY_INTERNAL__: boolean;
102+
103+
public constructor() {
104+
this.__SENTRY_INTERNAL__ = true;
105+
}
106+
107+
/**
108+
* Catches exceptions and reports them to Sentry unless they are HttpExceptions.
109+
*/
110+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
111+
public catch(exception: unknown, host: ArgumentsHost): void {
112+
// neither report nor log HttpExceptions
113+
if (exception instanceof HttpException) {
114+
throw exception;
115+
}
116+
if (exception instanceof Error) {
117+
SentryGlobalGraphQLFilter._logger.error(exception.message, exception.stack);
118+
}
119+
captureException(exception);
120+
throw exception;
121+
}
122+
}
123+
Catch()(SentryGlobalGraphQLFilter);
124+
export { SentryGlobalGraphQLFilter };
125+
81126
/**
82127
* Service to set up Sentry performance tracing for Nest.js applications.
83128
*/
84129
class SentryService implements OnModuleInit {
85-
public static readonly __SENTRY_INTERNAL__ = true;
130+
public readonly __SENTRY_INTERNAL__: boolean;
131+
132+
public constructor() {
133+
this.__SENTRY_INTERNAL__ = true;
134+
}
86135

87136
/**
88137
* Initializes the Sentry service and registers span attributes.

0 commit comments

Comments
 (0)