0
# Stack Processing & Parsing
1
2
**DEPRECATED**: Import all functions from `@sentry/core` instead of `@sentry/utils`.
3
4
Stack trace parsing, manipulation, and filtering utilities for error processing and debugging across different JavaScript environments.
5
6
## Capabilities
7
8
### Stack Parser Creation
9
10
Core functionality for creating customizable stack parsers.
11
12
```typescript { .api }
13
/**
14
* A function that parses a single line of a stack trace
15
*/
16
type StackLineParser = (line: string) => StackFrame | undefined;
17
18
/**
19
* A function that parses a complete stack trace
20
*/
21
type StackParser = (stack: string, skipFirst?: number) => StackFrame[];
22
23
/**
24
* Creates a stack parser by combining multiple line parsers
25
* @param parsers - Array of line parsers to try in order
26
* @returns Combined stack parser function
27
*/
28
function createStackParser(...parsers: StackLineParser[]): StackParser;
29
30
/**
31
* Creates a stack parser from parser configuration options
32
* @param stackParserOptions - Configuration options for the parser
33
* @returns Configured stack parser
34
*/
35
function stackParserFromStackParserOptions(stackParserOptions: StackParserOptions): StackParser;
36
```
37
38
### Built-in Line Parsers
39
40
Pre-built parsers for common JavaScript environments.
41
42
```typescript { .api }
43
/**
44
* Stack line parser optimized for Node.js stack traces
45
* @returns Parser function for Node.js format stack lines
46
*/
47
function nodeStackLineParser(): StackLineParser;
48
49
/**
50
* Node.js-specific parsing utilities and constants
51
*/
52
declare const node: {
53
/** Standard Node.js stack line parser */
54
nodeStackLineParser: () => StackLineParser;
55
/** Additional Node.js parsing utilities */
56
[key: string]: any;
57
};
58
```
59
60
### Stack Frame Processing
61
62
Functions for working with parsed stack frames.
63
64
```typescript { .api }
65
interface StackFrame {
66
/** Source file name */
67
filename?: string;
68
/** Function name */
69
function?: string;
70
/** Module name */
71
module?: string;
72
/** Platform identifier */
73
platform?: string;
74
/** Line number */
75
lineno?: number;
76
/** Column number */
77
colno?: number;
78
/** Absolute file path */
79
abs_path?: string;
80
/** Source code line at error */
81
context_line?: string;
82
/** Lines before the error */
83
pre_context?: string[];
84
/** Lines after the error */
85
post_context?: string[];
86
/** Whether frame is from app code (not libraries) */
87
in_app?: boolean;
88
/** Memory address (native code) */
89
instruction_addr?: string;
90
/** Address mode */
91
addr_mode?: string;
92
/** Package name */
93
package?: string;
94
/** Symbol name */
95
symbol?: string;
96
/** Symbol address */
97
symbol_addr?: string;
98
/** Trust level of the frame */
99
trust?: string;
100
}
101
102
/**
103
* Extracts stack frames from an event object
104
* @param event - Event containing exception data
105
* @returns Array of stack frames or undefined
106
*/
107
function getFramesFromEvent(event: Event): StackFrame[] | undefined;
108
109
/**
110
* Parses stack frames from an error object using the provided parser
111
* @param parser - Stack parser to use
112
* @param err - Error object with stack trace
113
* @returns Array of parsed stack frames
114
*/
115
function parseStackFrames(parser: StackParser, err: Error & { stacktrace?: string }): StackFrame[];
116
117
/**
118
* Converts a DevTools call frame to a Sentry stack frame
119
* @param callFrame - DevTools protocol call frame
120
* @returns Sentry stack frame
121
*/
122
function callFrameToStackFrame(callFrame: any): StackFrame;
123
```
124
125
### Stack Manipulation
126
127
Utilities for filtering and transforming stack traces.
128
129
```typescript { .api }
130
/**
131
* Removes Sentry-related frames from stack and reverses order
132
* @param frames - Array of stack frames to process
133
* @returns Filtered and reversed stack frames
134
*/
135
function stripSentryFramesAndReverse(frames: StackFrame[]): StackFrame[];
136
137
/**
138
* Determines if a filename should be marked as "in_app" (application code)
139
* @param filename - File path to check
140
* @param inAppIncludes - Patterns for files to include as app code
141
* @param inAppExcludes - Patterns for files to exclude from app code
142
* @returns True if filename represents application code
143
*/
144
function filenameIsInApp(
145
filename: string,
146
inAppIncludes?: Array<string | RegExp>,
147
inAppExcludes?: Array<string | RegExp>
148
): boolean;
149
150
/**
151
* Extracts function name from a stack frame
152
* @param frame - Stack frame to analyze
153
* @returns Function name or undefined
154
*/
155
function getFunctionName(frame: StackFrame): string | undefined;
156
```
157
158
**Usage Examples:**
159
160
```typescript
161
import {
162
createStackParser,
163
nodeStackLineParser,
164
parseStackFrames,
165
stripSentryFramesAndReverse,
166
filenameIsInApp
167
} from "@sentry/core";
168
169
// Create a parser for Node.js environments
170
const parser = createStackParser(nodeStackLineParser());
171
172
// Parse an error's stack trace
173
function processError(error: Error) {
174
const frames = parseStackFrames(parser, error);
175
176
// Filter out Sentry internal frames
177
const cleanFrames = stripSentryFramesAndReverse(frames);
178
179
// Mark frames as in-app or library code
180
const processedFrames = cleanFrames.map(frame => ({
181
...frame,
182
in_app: frame.filename ? filenameIsInApp(
183
frame.filename,
184
[/^\/app\//, /src\//], // Include app patterns
185
[/node_modules/, /dist\/vendor/] // Exclude library patterns
186
) : false
187
}));
188
189
return processedFrames;
190
}
191
```
192
193
### Stack Constants and Utilities
194
195
Constants and helper functions for stack processing.
196
197
```typescript { .api }
198
/**
199
* Constant representing an unknown function name
200
*/
201
declare const UNKNOWN_FUNCTION: string;
202
203
/**
204
* Adds source code context to a stack frame
205
* @param frame - Stack frame to enhance
206
* @param linesOfContext - Number of context lines to include
207
* @returns Enhanced frame with context
208
*/
209
function addContextToFrame(
210
frame: StackFrame,
211
linesOfContext?: number
212
): StackFrame;
213
```
214
215
## Stack Processing Patterns
216
217
### Error Processing Pipeline
218
219
Complete pipeline for processing error stack traces:
220
221
```typescript
222
import {
223
createStackParser,
224
nodeStackLineParser,
225
parseStackFrames,
226
stripSentryFramesAndReverse,
227
filenameIsInApp,
228
addContextToFrame,
229
getFunctionName
230
} from "@sentry/core";
231
232
class StackProcessor {
233
private parser: StackParser;
234
235
constructor() {
236
// Create parser with multiple fallbacks
237
this.parser = createStackParser(
238
nodeStackLineParser(),
239
// Could add browser parsers here for universal code
240
);
241
}
242
243
processError(error: Error): ProcessedStackTrace {
244
// Parse the raw stack trace
245
let frames = parseStackFrames(this.parser, error);
246
247
// Remove Sentry internal frames and reverse order
248
frames = stripSentryFramesAndReverse(frames);
249
250
// Enhance frames with additional information
251
frames = frames.map(frame => this.enhanceFrame(frame));
252
253
return {
254
frames,
255
frameCount: frames.length,
256
inAppFrameCount: frames.filter(f => f.in_app).length
257
};
258
}
259
260
private enhanceFrame(frame: StackFrame): StackFrame {
261
let enhanced = { ...frame };
262
263
// Determine if frame is from application code
264
if (enhanced.filename) {
265
enhanced.in_app = filenameIsInApp(
266
enhanced.filename,
267
[/^\/app\//, /src\//, /lib\/(?!node_modules)/],
268
[/node_modules/, /vendor/, /dist\/external/]
269
);
270
}
271
272
// Extract function name if missing
273
if (!enhanced.function) {
274
enhanced.function = getFunctionName(enhanced) || UNKNOWN_FUNCTION;
275
}
276
277
// Add source context if available
278
enhanced = addContextToFrame(enhanced, 5);
279
280
return enhanced;
281
}
282
}
283
284
interface ProcessedStackTrace {
285
frames: StackFrame[];
286
frameCount: number;
287
inAppFrameCount: number;
288
}
289
```
290
291
### Custom Line Parser
292
293
Creating custom parsers for specific stack trace formats:
294
295
```typescript
296
import { createStackParser, StackLineParser } from "@sentry/core";
297
298
// Custom parser for a specific logging format
299
const customLogParser: StackLineParser = (line: string) => {
300
// Example format: "at functionName (/path/to/file.js:123:45)"
301
const match = line.match(/^\s*at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)$/);
302
303
if (!match) {
304
return undefined;
305
}
306
307
const [, functionName, filename, lineno, colno] = match;
308
309
return {
310
function: functionName,
311
filename,
312
lineno: parseInt(lineno, 10),
313
colno: parseInt(colno, 10),
314
in_app: !filename.includes('node_modules')
315
};
316
};
317
318
// Combine with existing parsers
319
const hybridParser = createStackParser(
320
customLogParser,
321
nodeStackLineParser()
322
);
323
```
324
325
### Stack Frame Filtering
326
327
Advanced filtering based on various criteria:
328
329
```typescript
330
import { StackFrame } from "@sentry/core";
331
332
class StackFilter {
333
static filterInternalFrames(frames: StackFrame[]): StackFrame[] {
334
return frames.filter(frame => {
335
// Remove frames without file information
336
if (!frame.filename) return false;
337
338
// Remove known internal libraries
339
const internalPatterns = [
340
/node_modules\/@sentry\//,
341
/node_modules\/source-map-support/,
342
/internal\/process/,
343
/<anonymous>/
344
];
345
346
return !internalPatterns.some(pattern =>
347
pattern.test(frame.filename!)
348
);
349
});
350
}
351
352
static limitFrameCount(frames: StackFrame[], maxFrames: number = 50): StackFrame[] {
353
if (frames.length <= maxFrames) {
354
return frames;
355
}
356
357
// Keep top frames and some bottom frames
358
const topFrames = frames.slice(0, Math.floor(maxFrames * 0.7));
359
const bottomFrames = frames.slice(-(Math.floor(maxFrames * 0.3)));
360
361
return [
362
...topFrames,
363
{
364
function: '... truncated ...',
365
filename: `... ${frames.length - maxFrames} frames omitted ...`,
366
lineno: 0,
367
colno: 0
368
},
369
...bottomFrames
370
];
371
}
372
373
static prioritizeAppFrames(frames: StackFrame[]): StackFrame[] {
374
const appFrames = frames.filter(f => f.in_app);
375
const libraryFrames = frames.filter(f => !f.in_app);
376
377
// Show app frames first, then most relevant library frames
378
return [
379
...appFrames,
380
...libraryFrames.slice(0, 10) // Limit library frames
381
];
382
}
383
}
384
```
385
386
## Types
387
388
```typescript { .api }
389
interface StackParserOptions {
390
iteratee?: (frames: StackFrame[]) => StackFrame[];
391
[key: string]: any;
392
}
393
394
interface Exception {
395
type?: string;
396
value?: string;
397
stacktrace?: {
398
frames?: StackFrame[];
399
frames_omitted?: [number, number];
400
};
401
mechanism?: {
402
type: string;
403
handled?: boolean;
404
[key: string]: any;
405
};
406
}
407
```
408
409
**Migration Note**: All stack processing functions have been moved from `@sentry/utils` to `@sentry/core`. Update your imports accordingly.