Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 | 8x 8x 8x 8x 8x 4x 4x 4x 4x 4x 8x 8x 8x 8x 8x 8x 5x 5x 5x 5x 5x 5x 4x 4x 4x 2x 2x 4x 4x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 5x 5x 4x 4x 4x 4x 4x 2x 2x 2x 8x 8x 8x 8x 8x 7x 7x 7x 7x 1x 7x 1x 1x 1x 1x 2x | /**
* Coherent.js Error Boundary
*
* Catches rendering errors and provides fallback UI.
* Similar to React's Error Boundaries but for Coherent.js.
*
* @module components/error-boundary
*/
/**
* Error boundary state
*/
class ErrorBoundaryState {
constructor() {
this.hasError = false;
this.error = null;
this.errorInfo = null;
this.errorCount = 0;
this.lastError = null;
}
reset() {
this.hasError = false;
this.error = null;
this.errorInfo = null;
}
setError(error, errorInfo = {}) {
this.hasError = true;
this.error = error;
this.errorInfo = errorInfo;
this.errorCount++;
this.lastError = Date.now();
}
}
/**
* Create an error boundary
*
* @param {Object} options - Error boundary options
* @param {Object|Function} options.fallback - Fallback component or function
* @param {Function} [options.onError] - Error callback
* @param {Function} [options.onReset] - Reset callback
* @param {Array<string>} [options.resetKeys] - Keys that trigger reset
* @param {boolean} [options.resetOnPropsChange] - Reset on props change
* @param {number} [options.maxErrors] - Maximum errors before permanent fallback
* @param {number} [options.resetTimeout] - Auto-reset timeout in ms
* @returns {Function} Error boundary wrapper function
*
* @example
* const boundary = createErrorBoundary({
* fallback: { div: { text: 'Something went wrong' } },
* onError: (error, errorInfo) => console.error(error),
* resetKeys: ['userId']
* });
*
* const SafeComponent = boundary(MyComponent);
*/
export function createErrorBoundary(options = {}) {
const {
fallback = { div: { className: 'error-boundary', text: 'An error occurred' } },
onError = null,
onReset = null,
resetKeys = [],
resetOnPropsChange = false,
maxErrors = Infinity,
resetTimeout = null
} = options;
const state = new ErrorBoundaryState();
let previousProps = {};
let resetTimer = null;
/**
* Wrap a component with error boundary
*/
return function errorBoundaryWrapper(component) {
return function wrappedComponent(props = {}) {
try {
// Check if we should reset based on props
Iif (resetOnPropsChange && shouldReset(props, previousProps, resetKeys)) {
state.reset();
if (onReset) {
onReset();
}
}
previousProps = { ...props };
// If we have an error and haven't exceeded max errors
Iif (state.hasError) {
if (state.errorCount >= maxErrors) {
// Permanent fallback
return typeof fallback === 'function'
? fallback(state.error, state.errorInfo, { permanent: true })
: fallback;
}
// Return fallback with reset option
const fallbackComponent = typeof fallback === 'function'
? fallback(state.error, state.errorInfo, {
reset: () => {
state.reset();
if (onReset) {
onReset();
}
},
errorCount: state.errorCount
})
: fallback;
return fallbackComponent;
}
// Try to render the component
const result = typeof component === 'function'
? component(props)
: component;
return result;
} catch (error) {
// Capture error
const errorInfo = {
componentStack: error.stack,
props,
timestamp: Date.now()
};
state.setError(error, errorInfo);
// Call error callback
if (onError) {
try {
onError(error, errorInfo);
} catch (callbackError) {
console.error('Error in onError callback:', callbackError);
}
}
// Set auto-reset timer if configured
Iif (resetTimeout && !resetTimer) {
resetTimer = setTimeout(() => {
state.reset();
resetTimer = null;
if (onReset) {
onReset();
}
}, resetTimeout);
}
// Return fallback
return typeof fallback === 'function'
? fallback(error, errorInfo, {
reset: () => {
state.reset();
if (resetTimer) {
clearTimeout(resetTimer);
resetTimer = null;
}
if (onReset) {
onReset();
}
},
errorCount: state.errorCount
})
: fallback;
}
};
};
}
/**
* Check if error boundary should reset based on props
*/
function shouldReset(newProps, oldProps, resetKeys) {
if (resetKeys.length === 0) {
return false;
}
return resetKeys.some(key => newProps[key] !== oldProps[key]);
}
/**
* Create a default error fallback component
*
* @param {Object} options - Fallback options
* @returns {Function} Fallback component function
*/
export function createErrorFallback(options = {}) {
const {
title = 'Something went wrong',
showError = true,
showStack = false,
showReset = true,
className = 'error-boundary-fallback',
style = {}
} = options;
return function errorFallback(error, errorInfo, context = {}) {
const children = [
{
h2: {
className: 'error-title',
text: title
}
}
];
Eif (showError && error) {
children.push({
p: {
className: 'error-message',
text: error.message || 'Unknown error'
}
});
}
Iif (showStack && error && error.stack) {
children.push({
pre: {
className: 'error-stack',
text: error.stack
}
});
}
Iif (showReset && context.reset && !context.permanent) {
children.push({
button: {
className: 'error-reset-button',
text: 'Try Again',
onclick: context.reset
}
});
}
Iif (context.errorCount > 1) {
children.push({
p: {
className: 'error-count',
text: `Error occurred ${context.errorCount} times`
}
});
}
return {
div: {
className,
style: {
padding: '20px',
border: '1px solid #f44336',
borderRadius: '4px',
backgroundColor: '#ffebee',
color: '#c62828',
...style
},
children
}
};
};
}
/**
* Wrap multiple components with the same error boundary
*
* @param {Object} options - Error boundary options
* @param {Object} components - Components to wrap
* @returns {Object} Wrapped components
*
* @example
* const safeComponents = withErrorBoundary(
* { fallback: ErrorFallback },
* { Header, Footer, Content }
* );
*/
export function withErrorBoundary(options, components) {
const boundary = createErrorBoundary(options);
const wrapped = {};
Object.entries(components).forEach(([name, component]) => {
wrapped[name] = boundary(component);
});
return wrapped;
}
/**
* Error boundary for async components
*
* @param {Object} options - Error boundary options
* @returns {Function} Async error boundary wrapper
*/
export function createAsyncErrorBoundary(options = {}) {
const {
fallback = { div: { text: 'Loading...' } },
errorFallback = { div: { text: 'Failed to load' } },
onError = null,
timeout = 10000
} = options;
return function asyncBoundaryWrapper(asyncComponent) {
return async function wrappedAsyncComponent(props = {}) {
try {
// Set timeout
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => reject(new Error('Component load timeout')), timeout);
});
// Race between component load and timeout
const result = await Promise.race([
typeof asyncComponent === 'function'
? asyncComponent(props)
: asyncComponent,
timeoutPromise
]);
return result ?? fallback;
} catch (error) {
Iif (onError) {
onError(error, { props, async: true });
}
return typeof errorFallback === 'function'
? errorFallback(error, { props })
: errorFallback;
}
};
};
}
/**
* Global error handler for uncaught errors
*/
export class GlobalErrorHandler {
constructor(options = {}) {
this.options = options;
this.errors = [];
this.maxErrors = options.maxErrors || 100;
this.onError = options.onError || null;
this.enabled = options.enabled !== false;
}
/**
* Capture an error
*/
captureError(error, context = {}) {
Iif (!this.enabled) return;
const errorEntry = {
error,
context,
timestamp: Date.now(),
stack: error.stack
};
this.errors.push(errorEntry);
// Limit stored errors
if (this.errors.length > this.maxErrors) {
this.errors.shift();
}
// Call error callback
Iif (this.onError) {
try {
this.onError(error, context);
} catch (callbackError) {
console.error('Error in global error handler callback:', callbackError);
}
}
}
/**
* Get all captured errors
*/
getErrors() {
return [...this.errors];
}
/**
* Clear all errors
*/
clearErrors() {
this.errors = [];
}
/**
* Get error statistics
*/
getStats() {
return {
totalErrors: this.errors.length,
enabled: this.enabled,
maxErrors: this.maxErrors
};
}
/**
* Enable error handler
*/
enable() {
this.enabled = true;
}
/**
* Disable error handler
*/
disable() {
this.enabled = false;
}
}
/**
* Create a global error handler
*/
export function createGlobalErrorHandler(options = {}) {
return new GlobalErrorHandler(options);
}
/**
* Export all error boundary utilities
*/
export default {
createErrorBoundary,
createErrorFallback,
withErrorBoundary,
createAsyncErrorBoundary,
GlobalErrorHandler,
createGlobalErrorHandler
};
|