Skip to content

ref(node): Add source code context from LinkedErrors so integration order doesn't matter #4753

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 1 commit into from
Mar 23, 2022
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
29 changes: 17 additions & 12 deletions packages/node/src/integrations/contextlines.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,8 @@ export class ContextLines implements Integration {

public constructor(private readonly _options: ContextLinesOptions = {}) {}

/**
* @inheritDoc
*/
public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void): void {
/** Get's the number of context lines to add */
private get _contextLines(): number {
// This is only here to copy frameContextLines from init options if it hasn't
// been set via this integrations constructor.
//
Expand All @@ -65,18 +63,22 @@ export class ContextLines implements Integration {
this._options.frameContextLines = initOptions?.frameContextLines;
}

const contextLines =
this._options.frameContextLines !== undefined ? this._options.frameContextLines : DEFAULT_LINES_OF_CONTEXT;
return this._options.frameContextLines !== undefined ? this._options.frameContextLines : DEFAULT_LINES_OF_CONTEXT;
}

addGlobalEventProcessor(event => this.addSourceContext(event, contextLines));
/**
* @inheritDoc
*/
public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void): void {
addGlobalEventProcessor(event => this.addSourceContext(event));
}

/** Processes an event and adds context lines */
public async addSourceContext(event: Event, contextLines: number): Promise<Event> {
if (contextLines > 0 && event.exception?.values) {
public async addSourceContext(event: Event): Promise<Event> {
if (this._contextLines > 0 && event.exception?.values) {
for (const exception of event.exception.values) {
if (exception.stacktrace?.frames) {
await this._addSourceContextToFrames(exception.stacktrace.frames, contextLines);
await this.addSourceContextToFrames(exception.stacktrace.frames);
}
}
}
Expand All @@ -85,9 +87,12 @@ export class ContextLines implements Integration {
}

/** Adds context lines to frames */
public async _addSourceContextToFrames(frames: StackFrame[], contextLines: number): Promise<void> {
public async addSourceContextToFrames(frames: StackFrame[]): Promise<void> {
const contextLines = this._contextLines;

for (const frame of frames) {
if (frame.filename) {
// Only add context if we have a filename and it hasn't already been added
if (frame.filename && frame.context_line === undefined) {
const sourceFile = await _readSourceFile(frame.filename);

if (sourceFile) {
Expand Down
14 changes: 11 additions & 3 deletions packages/node/src/integrations/linkederrors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Event, EventHint, Exception, ExtendedError, Integration } from '@sentry
import { isInstanceOf, resolvedSyncPromise, SyncPromise } from '@sentry/utils';

import { exceptionFromError } from '../eventbuilder';
import { ContextLines } from './contextlines';

const DEFAULT_KEY = 'cause';
const DEFAULT_LIMIT = 5;
Expand Down Expand Up @@ -76,14 +77,21 @@ export class LinkedErrors implements Integration {
/**
* @inheritDoc
*/
private _walkErrorTree(error: ExtendedError, key: string, stack: Exception[] = []): PromiseLike<Exception[]> {
private async _walkErrorTree(error: ExtendedError, key: string, stack: Exception[] = []): Promise<Exception[]> {
if (!isInstanceOf(error[key], Error) || stack.length + 1 >= this._limit) {
return resolvedSyncPromise(stack);
return Promise.resolve(stack);
}

const exception = exceptionFromError(error[key]);

return new SyncPromise<Exception[]>((resolve, reject) => {
// If the ContextLines integration is enabled, we add source code context to linked errors
// because we can't guarantee the order that integrations are run.
const contextLines = getCurrentHub().getIntegration(ContextLines);
if (contextLines && exception.stacktrace?.frames) {
await contextLines.addSourceContextToFrames(exception.stacktrace.frames);
}

return new Promise<Exception[]>((resolve, reject) => {
void this._walkErrorTree(error[key], key, [exception, ...stack])
.then(resolve)
.then(null, () => {
Expand Down
3 changes: 1 addition & 2 deletions packages/node/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export const defaultIntegrations = [
// Common
new CoreIntegrations.InboundFilters(),
new CoreIntegrations.FunctionToString(),
new ContextLines(),
// Native Wrappers
new Console(),
new Http(),
Expand All @@ -20,8 +21,6 @@ export const defaultIntegrations = [
new OnUnhandledRejection(),
// Misc
new LinkedErrors(),
// ContextLines must come after LinkedErrors so that context is added to linked errors
new ContextLines(),
];

/**
Expand Down
8 changes: 5 additions & 3 deletions packages/node/test/context-lines.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ describe('ContextLines', () => {
let readFileSpy: jest.SpyInstance;
let contextLines: ContextLines;

async function addContext(frames: StackFrame[], lines: number = 7): Promise<void> {
await contextLines.addSourceContext({ exception: { values: [{ stacktrace: { frames } }] } }, lines);
async function addContext(frames: StackFrame[]): Promise<void> {
await contextLines.addSourceContext({ exception: { values: [{ stacktrace: { frames } }] } });
}

beforeEach(() => {
Expand Down Expand Up @@ -97,10 +97,12 @@ describe('ContextLines', () => {
});

test('parseStack with no context', async () => {
contextLines = new ContextLines({ frameContextLines: 0 });

expect.assertions(1);
const frames = parseStackFrames(new Error('test'));

await addContext(frames, 0);
await addContext(frames);
expect(readFileSpy).toHaveBeenCalledTimes(0);
});
});
Expand Down
6 changes: 3 additions & 3 deletions packages/node/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
Scope,
} from '../src';
import { NodeBackend } from '../src/backend';
import { LinkedErrors } from '../src/integrations';
import { ContextLines, LinkedErrors } from '../src/integrations';

jest.mock('@sentry/core', () => {
const original = jest.requireActual('@sentry/core');
Expand Down Expand Up @@ -199,11 +199,11 @@ describe('SentryNode', () => {
}
});

test.only('capture a linked exception with pre/post context', done => {
test('capture a linked exception with pre/post context', done => {
Copy link
Member

Choose a reason for hiding this comment

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

nice catch!

expect.assertions(15);
getCurrentHub().bindClient(
new NodeClient({
integrations: i => [new LinkedErrors(), ...i],
integrations: [new ContextLines(), new LinkedErrors()],
beforeSend: (event: Event) => {
expect(event.exception).not.toBeUndefined();
expect(event.exception!.values![1]).not.toBeUndefined();
Expand Down