diff --git a/.cursor/BUGBOT.md b/.cursor/BUGBOT.md index 29f9a82844ea..a7e2b12af6cc 100644 --- a/.cursor/BUGBOT.md +++ b/.cursor/BUGBOT.md @@ -56,9 +56,7 @@ Keep reviews high-signal. Prefer actionable, high-confidence findings over specu - `SEMANTIC_ATTRIBUTE_SENTRY_OP` (`'sentry.op'`) with a proper span op - Span ops should be lower case only, and use snake_case. The `.` character is used to delimit op parts. - flag any non-conforming op values as invalid and link to the span op specification (https://develop.sentry.dev/sdk/telemetry/traces/span-operations/) -- When calling `captureException`, always make sure that the `mechanism` is set: - - `handled`: must be set to `true` or `false` - - `type`: must be a proper identifier (i.e. identify the integration and part in the integration that caught the exception). The value should follow the same naming convention as `SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN`, and align with the surrounding span's origin when one exists. +- `sdk/require-exception-mechanism` checks that `captureException` sets `mechanism.handled` and `mechanism.type`. Still check that `mechanism.type` identifies the integration and the part of it that caught the exception, follows the same naming convention as `SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN`, and aligns with the surrounding span's origin when one exists. - For automated structured logs, always set `sentry.origin` with a proper origin (same character rules as span origins). - When calling any `startSpan` API, check how errors in the instrumented code are handled: - Generally, errors in instrumented code should be allowed to bubble up so the end user can handle them. If they remain unhandled, they will eventually be captured by Sentry through the SDK's global error handlers — so instrumentation code should typically **not** call `captureException` itself. diff --git a/.oxlintrc.base.json b/.oxlintrc.base.json index a2256c9a2803..883e2c6f85ec 100644 --- a/.oxlintrc.base.json +++ b/.oxlintrc.base.json @@ -259,6 +259,7 @@ "no-restricted-globals": ["error", "window", "document", "location", "navigator"], "no-eval": "error", "no-new-func": "error", + "sdk/require-exception-mechanism": "error", "sdk/no-unsafe-html-writes": "error" } }, diff --git a/packages/browser/src/helpers.ts b/packages/browser/src/helpers.ts index 65255d987e7d..7a1099198514 100644 --- a/packages/browser/src/helpers.ts +++ b/packages/browser/src/helpers.ts @@ -173,7 +173,7 @@ export function wrap( return event; }); - // no need to add a mechanism here, we already add it via an event processor above + // oxlint-disable-next-line sdk/require-exception-mechanism -- mechanism is set by the event processor above captureException(ex); }); diff --git a/packages/bundler-plugins/src/core/build-plugin-manager.ts b/packages/bundler-plugins/src/core/build-plugin-manager.ts index 838a9cc8e3d4..bfc688ac9357 100644 --- a/packages/bundler-plugins/src/core/build-plugin-manager.ts +++ b/packages/bundler-plugins/src/core/build-plugin-manager.ts @@ -1,4 +1,5 @@ /* oxlint-disable max-lines */ +/* oxlint-disable sdk/require-exception-mechanism -- these calls report failures of the plugin itself to its own telemetry, not user errors */ import { closeSession, DEFAULT_ENVIRONMENT, makeSession, setMeasurement, startSpan } from '@sentry/core'; import * as dotenv from 'dotenv'; import * as fs from 'fs'; diff --git a/packages/core/src/exports.ts b/packages/core/src/exports.ts index ce531805a997..e19169453051 100644 --- a/packages/core/src/exports.ts +++ b/packages/core/src/exports.ts @@ -25,6 +25,7 @@ import { GLOBAL_OBJ } from './utils/worldwide'; * @returns the id of the captured Sentry event. */ export function captureException(exception: unknown, hint?: ExclusiveEventHintOrCaptureContext): string { + // oxlint-disable-next-line sdk/require-exception-mechanism -- public API, passes the caller's hint through return getCurrentScope().captureException(exception, parseEventHintOrCaptureContext(hint)); } diff --git a/packages/core/src/integrations/captureconsole.ts b/packages/core/src/integrations/captureconsole.ts index 8bf5f41929a8..e281a195a864 100644 --- a/packages/core/src/integrations/captureconsole.ts +++ b/packages/core/src/integrations/captureconsole.ts @@ -93,6 +93,7 @@ function consoleHandler(args: unknown[], level: string, handled: boolean): void const error = args.find(arg => arg instanceof Error); if (error) { + // oxlint-disable-next-line sdk/require-exception-mechanism -- mechanism is set by the event processor above captureException(error, captureContext); return; } diff --git a/packages/core/src/integrations/supabase.ts b/packages/core/src/integrations/supabase.ts index 0b6b7ab22bca..56d9aab1b29a 100644 --- a/packages/core/src/integrations/supabase.ts +++ b/packages/core/src/integrations/supabase.ts @@ -511,6 +511,7 @@ function instrumentPostgRESTFilterBuilder( supabaseContext.body = bodyPayload; } + // oxlint-disable-next-line sdk/require-exception-mechanism -- mechanism is set by the event processor below captureException(err, scope => { scope.addEventProcessor(e => { addExceptionMechanism(e, { diff --git a/packages/core/src/scope.ts b/packages/core/src/scope.ts index 7130bc5eb0d2..4e0cf6ce3538 100644 --- a/packages/core/src/scope.ts +++ b/packages/core/src/scope.ts @@ -681,6 +681,7 @@ export class Scope { const syntheticException = new Error('Sentry syntheticException'); + // oxlint-disable-next-line sdk/require-exception-mechanism -- public API, passes the caller's hint through this._client.captureException( exception, { diff --git a/packages/core/src/server-runtime-client.ts b/packages/core/src/server-runtime-client.ts index ff1376dbee5d..0feb8eabd08f 100644 --- a/packages/core/src/server-runtime-client.ts +++ b/packages/core/src/server-runtime-client.ts @@ -92,6 +92,7 @@ export class ServerRuntimeClient< */ public captureException(exception: unknown, hint?: EventHint, scope?: Scope): string { setCurrentRequestSessionErroredOrCrashed(hint); + // oxlint-disable-next-line sdk/require-exception-mechanism -- passes the caller's hint through return super.captureException(exception, hint, scope); } diff --git a/packages/core/src/trpc.ts b/packages/core/src/trpc.ts index d84f6f16f17b..698dda10f317 100644 --- a/packages/core/src/trpc.ts +++ b/packages/core/src/trpc.ts @@ -28,7 +28,7 @@ export interface SentryTrpcMiddlewareArguments { getRawInput?: () => Promise; } -const trpcCaptureContext = { mechanism: { handled: false, type: 'auto.rpc.trpc.middleware' } }; +const trpcMechanism = { handled: false, type: 'auto.rpc.trpc.middleware' }; function captureIfError(nextResult: unknown): void { // TODO: Set span status based on what TRPCError was encountered @@ -39,7 +39,7 @@ function captureIfError(nextResult: unknown): void { !nextResult.ok && 'error' in nextResult ) { - captureException(nextResult.error, trpcCaptureContext); + captureException(nextResult.error, { mechanism: trpcMechanism }); } } @@ -113,7 +113,7 @@ export function trpcMiddleware(options: SentryTrpcMiddlewareOptions = {}) { span.end(); return nextResult; } catch (e) { - captureException(e, trpcCaptureContext); + captureException(e, { mechanism: trpcMechanism }); span.end(); throw e; } diff --git a/packages/eslint-plugin-sdk/src/index.js b/packages/eslint-plugin-sdk/src/index.js index e1f27895b734..10fda6af238d 100644 --- a/packages/eslint-plugin-sdk/src/index.js +++ b/packages/eslint-plugin-sdk/src/index.js @@ -17,6 +17,7 @@ module.exports = { 'no-focused-tests': require('./rules/no-focused-tests'), 'no-skipped-tests': require('./rules/no-skipped-tests'), 'no-unsafe-random-apis': require('./rules/no-unsafe-random-apis'), + 'require-exception-mechanism': require('./rules/require-exception-mechanism'), 'no-unfiltered-url-attributes': require('./rules/no-unfiltered-url-attributes'), 'no-unguarded-span-apis': require('./rules/no-unguarded-span-apis'), 'no-unsafe-html-writes': require('./rules/no-unsafe-html-writes'), diff --git a/packages/eslint-plugin-sdk/src/rules/require-exception-mechanism.js b/packages/eslint-plugin-sdk/src/rules/require-exception-mechanism.js new file mode 100644 index 000000000000..e14a992a387f --- /dev/null +++ b/packages/eslint-plugin-sdk/src/rules/require-exception-mechanism.js @@ -0,0 +1,112 @@ +'use strict'; + +/** + * Every exception the SDK captures on its own needs a `mechanism` with `handled` and `type`, so the + * event shows whether the error was handled and which integration caught it. Without it, the event + * falls back to `{ type: 'generic', handled: true }`. + * + * Flags `captureException(...)` and `.captureException(...)` unless the hint (second + * argument) is an object literal whose `mechanism` sets both `handled` and `type`. A `mechanism` + * that is not an object literal (a variable or a call) is trusted, and so is a capture context + * callback that returns `markEventUnhandled(scope, type)`. Public API wrappers that only + * pass a hint through, or code that sets the mechanism another way (for example with + * `addExceptionMechanism` in an event processor), should disable the rule on that line and say why. + */ + +function getKeyName(property) { + if (!property.computed && property.key.type === 'Identifier') { + return property.key.name; + } + if (property.key.type === 'Literal' && typeof property.key.value === 'string') { + return property.key.value; + } + return undefined; +} + +function findProperty(objectExpression, name) { + return objectExpression.properties.find(property => property.type === 'Property' && getKeyName(property) === name); +} + +function isCaptureException(callee) { + if (callee.type === 'Identifier') { + return callee.name === 'captureException'; + } + return ( + callee.type === 'MemberExpression' && + !callee.computed && + callee.property.type === 'Identifier' && + callee.property.name === 'captureException' + ); +} + +// The serverless SDKs set the mechanism with this helper, which adds `{ handled: false, type }` in an event processor. +function isMarkEventUnhandledCallback(hint) { + if (hint.type !== 'ArrowFunctionExpression' && hint.type !== 'FunctionExpression') { + return false; + } + + let returned = hint.body; + if (returned.type === 'BlockStatement') { + const lastStatement = returned.body[returned.body.length - 1]; + returned = lastStatement && lastStatement.type === 'ReturnStatement' ? lastStatement.argument : undefined; + } + + return ( + !!returned && + returned.type === 'CallExpression' && + returned.callee.type === 'Identifier' && + returned.callee.name === 'markEventUnhandled' && + returned.arguments.length === 2 + ); +} + +/** Returns the missing mechanism keys, or `undefined` when the mechanism is complete or not statically visible. */ +function getMissingKeys(hint) { + if (hint && isMarkEventUnhandledCallback(hint)) { + return undefined; + } + + if (!hint || hint.type !== 'ObjectExpression') { + return 'mechanism'; + } + + const mechanism = findProperty(hint, 'mechanism'); + if (!mechanism) { + return 'mechanism'; + } + + if (mechanism.value.type !== 'ObjectExpression') { + return undefined; + } + + const missing = ['handled', 'type'].filter(key => !findProperty(mechanism.value, key)); + return missing.length ? `mechanism.${missing.join(' and mechanism.')}` : undefined; +} + +module.exports = { + meta: { + type: 'problem', + docs: { + description: 'Require `captureException` calls in SDK code to set `mechanism.handled` and `mechanism.type`.', + }, + schema: [], + messages: { + missingMechanism: + '`captureException` is missing `{{missing}}`. Pass `{ mechanism: { handled, type } }` as the hint, with `type` naming the integration and part that caught the error (same format as span origins).', + }, + }, + create(context) { + return { + CallExpression(node) { + if (!isCaptureException(node.callee)) { + return; + } + + const missing = getMissingKeys(node.arguments[1]); + if (missing) { + context.report({ node, messageId: 'missingMechanism', data: { missing } }); + } + }, + }; + }, +}; diff --git a/packages/eslint-plugin-sdk/test/lib/rules/require-exception-mechanism.test.ts b/packages/eslint-plugin-sdk/test/lib/rules/require-exception-mechanism.test.ts new file mode 100644 index 000000000000..4eb9c57f2766 --- /dev/null +++ b/packages/eslint-plugin-sdk/test/lib/rules/require-exception-mechanism.test.ts @@ -0,0 +1,86 @@ +import { RuleTester } from 'eslint'; +import { describe, test } from 'vitest'; +// @ts-expect-error untyped module +import rule from '../../../src/rules/require-exception-mechanism'; + +describe('require-exception-mechanism', () => { + test('ruleTester', () => { + const ruleTester = new RuleTester({ + parserOptions: { + ecmaVersion: 2020, + }, + }); + + ruleTester.run('require-exception-mechanism', rule, { + valid: [ + { code: "captureException(e, { mechanism: { handled: false, type: 'auto.http.express' } });" }, + { code: "captureException(e, { mechanism: { type: 'auto.http.express', handled: true, data: {} } });" }, + { code: "scope.captureException(e, { mechanism: { handled: false, type: 'auto.http.express' } });" }, + { code: "Sentry.captureException(e, { ...hint, mechanism: { handled: false, type: 'auto.http.express' } });" }, + { code: "captureException(e, { 'mechanism': { 'handled': false, 'type': 'auto.http.express' } });" }, + { code: 'captureException(e, { mechanism: MECHANISM });' }, + { code: 'captureException(e, { mechanism: getMechanism(e) });' }, + { code: "captureException(e, scope => markEventUnhandled(scope, 'auto.function.aws_serverless.handler'));" }, + { + code: "captureException(e, function (scope) { return markEventUnhandled(scope, 'auto.function.serverless.gcp_http'); });", + }, + { code: 'captureMessage(message);' }, + { code: 'foo.captureExceptionLater(e);' }, + ], + invalid: [ + { + code: 'captureException(e);', + errors: [{ messageId: 'missingMechanism', data: { missing: 'mechanism' } }], + }, + { + code: 'captureException(e, hint);', + errors: [{ messageId: 'missingMechanism', data: { missing: 'mechanism' } }], + }, + { + code: 'captureException(e, scope => scope);', + errors: [{ messageId: 'missingMechanism', data: { missing: 'mechanism' } }], + }, + { + code: 'captureException(e, scope => markEventUnhandled(scope));', + errors: [{ messageId: 'missingMechanism', data: { missing: 'mechanism' } }], + }, + { + code: "captureException(e, scope => { markEventUnhandled(scope, 'auto.x.y'); return otherScope; });", + errors: [{ messageId: 'missingMechanism', data: { missing: 'mechanism' } }], + }, + { + code: "captureException(e, { level: 'fatal' });", + errors: [{ messageId: 'missingMechanism', data: { missing: 'mechanism' } }], + }, + { + code: 'captureException(e, { ...hint });', + errors: [{ messageId: 'missingMechanism', data: { missing: 'mechanism' } }], + }, + { + code: 'captureException(e, { mechanism: { handled: false } });', + errors: [{ messageId: 'missingMechanism', data: { missing: 'mechanism.type' } }], + }, + { + code: "captureException(e, { mechanism: { type: 'auto.http.express' } });", + errors: [{ messageId: 'missingMechanism', data: { missing: 'mechanism.handled' } }], + }, + { + code: 'captureException(e, { mechanism: { ...base } });', + errors: [{ messageId: 'missingMechanism', data: { missing: 'mechanism.handled and mechanism.type' } }], + }, + { + code: 'scope.captureException(e);', + errors: [{ messageId: 'missingMechanism', data: { missing: 'mechanism' } }], + }, + { + code: 'this._client.captureException(e, hint, scope);', + errors: [{ messageId: 'missingMechanism', data: { missing: 'mechanism' } }], + }, + { + code: 'client?.captureException(e);', + errors: [{ messageId: 'missingMechanism', data: { missing: 'mechanism' } }], + }, + ], + }); + }); +}); diff --git a/packages/react/src/error.ts b/packages/react/src/error.ts index 9656f1497da9..ccfc42c1cc8f 100644 --- a/packages/react/src/error.ts +++ b/packages/react/src/error.ts @@ -58,6 +58,7 @@ export function captureReactException( setCause(error, errorBoundaryError); } + // oxlint-disable-next-line sdk/require-exception-mechanism -- public API, passes the caller's hint through return captureException(error, hint); } diff --git a/packages/remix/src/server/errors.ts b/packages/remix/src/server/errors.ts index 6cfaaefb0b78..870c2fa24511 100644 --- a/packages/remix/src/server/errors.ts +++ b/packages/remix/src/server/errors.ts @@ -53,6 +53,7 @@ export async function captureRemixServerException(err: unknown, name: string, re const objectifiedErr = objectify(err); + // oxlint-disable-next-line sdk/require-exception-mechanism -- mechanism is set by the event processor below captureException(isResponse(objectifiedErr) ? await extractResponseError(objectifiedErr) : objectifiedErr, scope => { scope.setSDKProcessingMetadata({ normalizedRequest }); diff --git a/packages/server-utils/src/integrations/pino.ts b/packages/server-utils/src/integrations/pino.ts index c970fa3fc0c3..54ff2940a00a 100644 --- a/packages/server-utils/src/integrations/pino.ts +++ b/packages/server-utils/src/integrations/pino.ts @@ -185,6 +185,7 @@ const _pinoIntegration = defineIntegration((userOptions: DeepPartial( // channel `error` lifecycle and the deferred `end` util so the two can't drift. const annotateSpanError = (span: Span, error: unknown): void => { if (opts?.captureError) { + // oxlint-disable-next-line sdk/require-exception-mechanism -- hint comes from `getErrorHint`, which sets a mechanism unless `captureError` overrides it captureException(error, getErrorHint(error)); } diff --git a/packages/vue/src/router.ts b/packages/vue/src/router.ts index 3f28ec5259b4..56b81f63deaa 100644 --- a/packages/vue/src/router.ts +++ b/packages/vue/src/router.ts @@ -73,7 +73,7 @@ export function instrumentVueRouter( // Vue Router 4+ uses `options.history` instead and does not expose `mode`. const isLegacyRouter = 'mode' in router; - router.onError(error => captureException(error, { mechanism: { handled: false } })); + router.onError(error => captureException(error, { mechanism: { handled: false, type: 'auto.function.vue.router' } })); // Use rest params to capture `next` without declaring it as a named parameter. // This keeps Function.length === 2, which tells Vue Router 4+/5+ to use the diff --git a/packages/vue/test/router.test.ts b/packages/vue/test/router.test.ts index bd0972bfcd09..9fd727ae8243 100644 --- a/packages/vue/test/router.test.ts +++ b/packages/vue/test/router.test.ts @@ -98,7 +98,9 @@ describe('instrumentVueRouter()', () => { onErrorCallback(testError); expect(captureExceptionSpy).toHaveBeenCalledTimes(1); - expect(captureExceptionSpy).toHaveBeenCalledWith(testError, { mechanism: { handled: false } }); + expect(captureExceptionSpy).toHaveBeenCalledWith(testError, { + mechanism: { handled: false, type: 'auto.function.vue.router' }, + }); }); it.each([