Skip to content
Open
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
4 changes: 1 addition & 3 deletions .cursor/BUGBOT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions .oxlintrc.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
},
Expand Down
2 changes: 1 addition & 1 deletion packages/browser/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ export function wrap<T extends WrappableFunction, NonFunction>(
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);
});

Expand Down
1 change: 1 addition & 0 deletions packages/bundler-plugins/src/core/build-plugin-manager.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/exports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}

Expand Down
1 change: 1 addition & 0 deletions packages/core/src/integrations/captureconsole.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/integrations/supabase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, {
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
{
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/server-runtime-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/trpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export interface SentryTrpcMiddlewareArguments<T> {
getRawInput?: () => Promise<unknown>;
}

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
Expand All @@ -39,7 +39,7 @@ function captureIfError(nextResult: unknown): void {
!nextResult.ok &&
'error' in nextResult
) {
captureException(nextResult.error, trpcCaptureContext);
captureException(nextResult.error, { mechanism: trpcMechanism });
}
}

Expand Down Expand Up @@ -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;
}
Expand Down
1 change: 1 addition & 0 deletions packages/eslint-plugin-sdk/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'),
Expand Down
112 changes: 112 additions & 0 deletions packages/eslint-plugin-sdk/src/rules/require-exception-mechanism.js
Original file line number Diff line number Diff line change
@@ -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 `<anything>.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 } });
}
},
};
},
};
Original file line number Diff line number Diff line change
@@ -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' } }],
},
],
});
});
});
1 change: 1 addition & 0 deletions packages/react/src/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down
1 change: 1 addition & 0 deletions packages/remix/src/server/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });

Expand Down
1 change: 1 addition & 0 deletions packages/server-utils/src/integrations/pino.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ const _pinoIntegration = defineIntegration((userOptions: DeepPartial<PinoOptions

const error = captureObj[errorKey];
if (error) {
// oxlint-disable-next-line sdk/require-exception-mechanism -- mechanism is set by the event processor above
captureException(error, captureContext);
return;
}
Expand Down
1 change: 1 addition & 0 deletions packages/server-utils/src/tracing-channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ export function bindTracingChannelToSpan<TData extends object>(
// 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));
}

Expand Down
2 changes: 1 addition & 1 deletion packages/vue/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion packages/vue/test/router.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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([
Expand Down
Loading