Skip to content

feat(node): Add setupFastifyErrorHandler utility #11061

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

Merged
merged 5 commits into from
Mar 13, 2024
Merged
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
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1021,7 +1021,7 @@ jobs:
'sveltekit',
'sveltekit-2',
'generic-ts3.8',
'node-experimental-fastify-app',
'node-fastify-app',
# TODO(v8): Re-enable hapi tests
# 'node-hapi-app',
'node-exports-test-app',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ const DEPENDENTS: Dependent[] = [
package: '@sentry/astro',
compareWith: nodeExports,
exports: Object.keys(SentryAstro),
ignoreExports: [
// Not needed for Astro
'setupFastifyErrorHandler',
],
},
{
package: '@sentry/bun',
Expand Down Expand Up @@ -82,13 +86,23 @@ const DEPENDENTS: Dependent[] = [
package: '@sentry/aws-serverless',
compareWith: nodeExports,
exports: Object.keys(SentryAWS),
ignoreExports: ['makeMain'],
ignoreExports: [
// legacy, to be removed...
'makeMain',
// Not needed for Serverless
'setupFastifyErrorHandler',
],
},
{
package: '@sentry/google-cloud-serverless',
compareWith: nodeExports,
exports: Object.keys(SentryGoogleCloud),
ignoreExports: ['makeMain'],
ignoreExports: [
// legacy, to be removed...
'makeMain',
// Not needed for Serverless
'setupFastifyErrorHandler',
],
},
{
package: '@sentry/sveltekit',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "node-experimental-fastify-app",
"name": "node-fastify-app",
"version": "1.0.0",
"private": true,
"scripts": {
Expand All @@ -17,7 +17,6 @@
"@sentry/opentelemetry": "latest || *",
"@types/node": "18.15.1",
"fastify": "4.23.2",
"fastify-plugin": "4.5.1",
"typescript": "4.9.5",
"ts-node": "10.9.1"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,12 @@ require('./tracing');

const Sentry = require('@sentry/node');
const { fastify } = require('fastify');
const fastifyPlugin = require('fastify-plugin');
const http = require('http');

const FastifySentry = fastifyPlugin(async (fastify, options) => {
fastify.decorateRequest('_sentryContext', null);

fastify.addHook('onError', async (_request, _reply, error) => {
Sentry.captureException(error);
});
});

const app = fastify();
const port = 3030;

app.register(FastifySentry);
Sentry.setupFastifyErrorHandler(app);

app.get('/test-success', function (req, res) {
res.send({ version: 'v1' });
Expand Down Expand Up @@ -61,6 +52,10 @@ app.get('/test-error', async function (req, res) {
res.send({ exceptionId });
});

app.get('/test-exception', async function (req, res) {
throw new Error('This is an exception');
});

app.listen({ port: port });

function makeHttpRequest(url) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ import { startEventProxyServer } from './event-proxy-server';

startEventProxyServer({
port: 3031,
proxyServerName: 'node-experimental-fastify-app',
proxyServerName: 'node-fastify-app',
});
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { expect, test } from '@playwright/test';
import axios, { AxiosError } from 'axios';
import { waitForError } from '../event-proxy-server';

const authToken = process.env.E2E_TEST_AUTH_TOKEN;
const sentryTestOrgSlug = process.env.E2E_TEST_SENTRY_ORG_SLUG;
Expand Down Expand Up @@ -37,3 +38,35 @@ test('Sends exception to Sentry', async ({ baseURL }) => {
)
.toBe(200);
});

test('Sends correct error event', async ({ baseURL }) => {
const errorEventPromise = waitForError('node-fastify-app', event => {
return !event.type && event.exception?.values?.[0]?.value === 'This is an exception';
});

try {
await axios.get(`${baseURL}/test-exception`);
} catch {
// this results in an error, but we don't care - we want to check the error event
}

const errorEvent = await errorEventPromise;

expect(errorEvent.exception?.values).toHaveLength(1);
expect(errorEvent.exception?.values?.[0]?.value).toBe('This is an exception');

expect(errorEvent.request).toEqual({
method: 'GET',
cookies: {},
headers: expect.any(Object),
url: 'http://localhost:3030/test-exception',
});

expect(errorEvent.transaction).toEqual('GET /test-exception');

expect(errorEvent.contexts?.trace).toEqual({
trace_id: expect.any(String),
span_id: expect.any(String),
parent_span_id: expect.any(String),
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import axios from 'axios';
import { waitForTransaction } from '../event-proxy-server';

test('Propagates trace for outgoing http requests', async ({ baseURL }) => {
const inboundTransactionPromise = waitForTransaction('node-experimental-fastify-app', transactionEvent => {
const inboundTransactionPromise = waitForTransaction('node-fastify-app', transactionEvent => {
return (
transactionEvent?.contexts?.trace?.op === 'http.server' &&
transactionEvent?.transaction === 'GET /test-inbound-headers'
);
});

const outboundTransactionPromise = waitForTransaction('node-experimental-fastify-app', transactionEvent => {
const outboundTransactionPromise = waitForTransaction('node-fastify-app', transactionEvent => {
return (
transactionEvent?.contexts?.trace?.op === 'http.server' &&
transactionEvent?.transaction === 'GET /test-outgoing-http'
Expand Down Expand Up @@ -118,14 +118,14 @@ test('Propagates trace for outgoing http requests', async ({ baseURL }) => {
});

test('Propagates trace for outgoing fetch requests', async ({ baseURL }) => {
const inboundTransactionPromise = waitForTransaction('node-experimental-fastify-app', transactionEvent => {
const inboundTransactionPromise = waitForTransaction('node-fastify-app', transactionEvent => {
return (
transactionEvent?.contexts?.trace?.op === 'http.server' &&
transactionEvent?.transaction === 'GET /test-inbound-headers'
);
});

const outboundTransactionPromise = waitForTransaction('node-experimental-fastify-app', transactionEvent => {
const outboundTransactionPromise = waitForTransaction('node-fastify-app', transactionEvent => {
return (
transactionEvent?.contexts?.trace?.op === 'http.server' &&
transactionEvent?.transaction === 'GET /test-outgoing-fetch'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const sentryTestProject = process.env.E2E_TEST_SENTRY_TEST_PROJECT;
const EVENT_POLLING_TIMEOUT = 90_000;

test('Sends an API route transaction', async ({ baseURL }) => {
const pageloadTransactionEventPromise = waitForTransaction('node-experimental-fastify-app', transactionEvent => {
const pageloadTransactionEventPromise = waitForTransaction('node-fastify-app', transactionEvent => {
return (
transactionEvent?.contexts?.trace?.op === 'http.server' &&
transactionEvent?.transaction === 'GET /test-transaction'
Expand Down Expand Up @@ -58,13 +58,13 @@ test('Sends an API route transaction', async ({ baseURL }) => {
spans: [
{
data: {
'plugin.name': 'fastify -> app-auto-0',
'plugin.name': 'fastify -> sentry-fastify-error-handler',
'fastify.type': 'request_handler',
'http.route': '/test-transaction',
'otel.kind': 'INTERNAL',
'sentry.origin': 'auto.http.otel.fastify',
},
description: 'request handler - fastify -> app-auto-0',
description: 'request handler - fastify -> sentry-fastify-error-handler',
parent_span_id: expect.any(String),
span_id: expect.any(String),
start_timestamp: expect.any(Number),
Expand Down
24 changes: 23 additions & 1 deletion docs/v8-node.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ If you want, you can use OpenTelemetry-native APIs to start spans, and Sentry wi
We support the following Node Frameworks out of the box:

- [Express](#express)
- Fastify
- [Fastify](#fastify)
- Koa
- Nest.js
- Hapi
Expand Down Expand Up @@ -101,3 +101,25 @@ Sentry.setupExpressErrorHandler(app);

app.listen(3000);
```

## Fastify
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should probably write a guide for Fastify in dour docs at some point (probably not a blocker but is this something for #11064?)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, once we update the docs for v8 we need to add guides for fastify, nest.js, and hapi, as well as updating the koa guides (and express, of course)! I'll add it to the issue, good point!


The following shows how you can setup Fastify instrumentation in v8. This will capture performance data & errors for
your Fastify app.

```js
const Sentry = require('@sentry/node');

Sentry.init({
dsn: '__DSN__',
tracesSampleRate: 1,
});

const { fastify } = require('fastify');
const app = fastify();
Sentry.setupFastifyErrorHandler(app);

// add routes etc. here

app.listen();
```
2 changes: 1 addition & 1 deletion packages/node-experimental/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export { onUnhandledRejectionIntegration } from './integrations/onunhandledrejec
export { anrIntegration } from './integrations/anr';

export { expressIntegration, expressErrorHandler, setupExpressErrorHandler } from './integrations/tracing/express';
export { fastifyIntegration } from './integrations/tracing/fastify';
export { fastifyIntegration, setupFastifyErrorHandler } from './integrations/tracing/fastify';
export { graphqlIntegration } from './integrations/tracing/graphql';
export { mongoIntegration } from './integrations/tracing/mongo';
export { mongooseIntegration } from './integrations/tracing/mongoose';
Expand Down
29 changes: 28 additions & 1 deletion packages/node-experimental/src/integrations/tracing/fastify.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { registerInstrumentations } from '@opentelemetry/instrumentation';
import { FastifyInstrumentation } from '@opentelemetry/instrumentation-fastify';
import { defineIntegration } from '@sentry/core';
import { captureException, defineIntegration } from '@sentry/core';
import type { IntegrationFn } from '@sentry/types';

import { addOriginToSpan } from '../../utils/addOriginToSpan';
Expand Down Expand Up @@ -28,3 +28,30 @@ const _fastifyIntegration = (() => {
* Capture tracing data for fastify.
*/
export const fastifyIntegration = defineIntegration(_fastifyIntegration);

// We inline the types we care about here
interface Fastify {
register: (plugin: unknown) => void;
addHook: (hook: string, handler: (request: unknown, reply: unknown, error: Error) => void) => void;
}

/**
* Setup an error handler for Fastify.
*/
export function setupFastifyErrorHandler(fastify: Fastify): void {
const plugin = Object.assign(
function (fastify: Fastify, options: unknown, done: () => void): void {
fastify.addHook('onError', async (_request, _reply, error) => {
captureException(error);
});

done();
},
{
[Symbol.for('skip-override')]: true,
[Symbol.for('fastify.display-name')]: 'sentry-fastify-error-handler',
},
);

fastify.register(plugin);
}