javascript / expert
Snippet
AggregateError Handling and Custom Stack Aggregation in React Error Boundaries
Demonstrates native AggregateError detection within React Error Boundaries. It processes batched promises or composite failures, extracting inner error stacks while formatting detailed diagnostic reports.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import React, { Component } from 'react';export class GroupedErrorBoundary extends Component {state = { aggregatedErrors: null };componentDidCatch(error, errorInfo) {if (error instanceof AggregateError) {const traceMap = error.errors.map(err => ({message: err.message,stack: err.stack?.split('\n').slice(0, 3).join('\n')}));this.setState({ aggregatedErrors: traceMap });} else {this.setState({ aggregatedErrors: [{ message: error.message, stack: errorInfo.componentStack }] });}}render() {if (this.state.aggregatedErrors) {return <div>Errors caught: {this.state.aggregatedErrors.length}</div>;}return this.props.children;}}
react
Breakdown
1
if (error instanceof AggregateError) {
Checks if the caught error is a composite standard AggregateError containing multiple inner errors.
2
const traceMap = error.errors.map(err => ({
Iterates through the errors array property of AggregateError to unwrap nested causes.
3
stack: err.stack?.split('\n').slice(0, 3).join('\n')
Truncates individual stack traces to normalize log footprint inside state.