Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

error-handling.md 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. # Error Handling and Resilience Checks
  2. ## Principle
  3. Treat expected failures explicitly: intercept network errors, assert UI fallbacks (error messages visible, retries triggered), and use scoped exception handling to ignore known errors while catching regressions. Test retry/backoff logic by forcing sequential failures (500 → timeout → success) and validate telemetry logging. Log captured errors with context (request payload, user/session) but redact secrets to keep artifacts safe for sharing.
  4. ## Rationale
  5. Tests fail for two reasons: genuine bugs or poor error handling in the test itself. Without explicit error handling patterns, tests become noisy (uncaught exceptions cause false failures) or silent (swallowing all errors hides real bugs). Scoped exception handling (Cypress.on('uncaught:exception'), page.on('pageerror')) allows tests to ignore documented, expected errors while surfacing unexpected ones. Resilience testing (retry logic, graceful degradation) ensures applications handle failures gracefully in production.
  6. ## Pattern Examples
  7. ### Example 1: Scoped Exception Handling (Expected Errors Only)
  8. **Context**: Handle known errors (Network failures, expected 500s) without masking unexpected bugs.
  9. **Implementation**:
  10. ```typescript
  11. // tests/e2e/error-handling.spec.ts
  12. import { test, expect } from '@playwright/test';
  13. /**
  14. * Scoped Error Handling Pattern
  15. * - Only ignore specific, documented errors
  16. * - Rethrow everything else to catch regressions
  17. * - Validate error UI and user experience
  18. */
  19. test.describe('API Error Handling', () => {
  20. test('should display error message when API returns 500', async ({ page }) => {
  21. // Scope error handling to THIS test only
  22. const consoleErrors: string[] = [];
  23. page.on('pageerror', (error) => {
  24. // Only swallow documented NetworkError
  25. if (error.message.includes('NetworkError: Failed to fetch')) {
  26. consoleErrors.push(error.message);
  27. return; // Swallow this specific error
  28. }
  29. // Rethrow all other errors (catch regressions!)
  30. throw error;
  31. });
  32. // Arrange: Mock 500 error response
  33. await page.route('**/api/users', (route) =>
  34. route.fulfill({
  35. status: 500,
  36. contentType: 'application/json',
  37. body: JSON.stringify({
  38. error: 'Internal server error',
  39. code: 'INTERNAL_ERROR',
  40. }),
  41. }),
  42. );
  43. // Act: Navigate to page that fetches users
  44. await page.goto('/dashboard');
  45. // Assert: Error UI displayed
  46. await expect(page.getByTestId('error-message')).toBeVisible();
  47. await expect(page.getByTestId('error-message')).toContainText(/error.*loading|failed.*load/i);
  48. // Assert: Retry button visible
  49. await expect(page.getByTestId('retry-button')).toBeVisible();
  50. // Assert: NetworkError was thrown and caught
  51. expect(consoleErrors).toContainEqual(expect.stringContaining('NetworkError'));
  52. });
  53. test('should NOT swallow unexpected errors', async ({ page }) => {
  54. let unexpectedError: Error | null = null;
  55. page.on('pageerror', (error) => {
  56. // Capture but don't swallow - test should fail
  57. unexpectedError = error;
  58. throw error;
  59. });
  60. // Arrange: App has JavaScript error (bug)
  61. await page.addInitScript(() => {
  62. // Simulate bug in app code
  63. (window as any).buggyFunction = () => {
  64. throw new Error('UNEXPECTED BUG: undefined is not a function');
  65. };
  66. });
  67. await page.goto('/dashboard');
  68. // Trigger buggy function
  69. await page.evaluate(() => (window as any).buggyFunction());
  70. // Assert: Test fails because unexpected error was NOT swallowed
  71. expect(unexpectedError).not.toBeNull();
  72. expect(unexpectedError?.message).toContain('UNEXPECTED BUG');
  73. });
  74. });
  75. ```
  76. **Cypress equivalent**:
  77. ```javascript
  78. // cypress/e2e/error-handling.cy.ts
  79. describe('API Error Handling', () => {
  80. it('should display error message when API returns 500', () => {
  81. // Scoped to this test only
  82. cy.on('uncaught:exception', (err) => {
  83. // Only swallow documented NetworkError
  84. if (err.message.includes('NetworkError')) {
  85. return false; // Prevent test failure
  86. }
  87. // All other errors fail the test
  88. return true;
  89. });
  90. // Arrange: Mock 500 error
  91. cy.intercept('GET', '**/api/users', {
  92. statusCode: 500,
  93. body: {
  94. error: 'Internal server error',
  95. code: 'INTERNAL_ERROR',
  96. },
  97. }).as('getUsers');
  98. // Act
  99. cy.visit('/dashboard');
  100. cy.wait('@getUsers');
  101. // Assert: Error UI
  102. cy.get('[data-cy="error-message"]').should('be.visible');
  103. cy.get('[data-cy="error-message"]').should('contain', 'error loading');
  104. cy.get('[data-cy="retry-button"]').should('be.visible');
  105. });
  106. it('should NOT swallow unexpected errors', () => {
  107. // No exception handler - test should fail on unexpected errors
  108. cy.visit('/dashboard');
  109. // Trigger unexpected error
  110. cy.window().then((win) => {
  111. // This should fail the test
  112. win.eval('throw new Error("UNEXPECTED BUG")');
  113. });
  114. // Test fails (as expected) - validates error detection works
  115. });
  116. });
  117. ```
  118. **Key Points**:
  119. - **Scoped handling**: page.on() / cy.on() scoped to specific tests
  120. - **Explicit allow-list**: Only ignore documented errors
  121. - **Rethrow unexpected**: Catch regressions by failing on unknown errors
  122. - **Error UI validation**: Assert user sees error message
  123. - **Logging**: Capture errors for debugging, don't swallow silently
  124. ---
  125. ### Example 2: Retry Validation Pattern (Network Resilience)
  126. **Context**: Test that retry/backoff logic works correctly for transient failures.
  127. **Implementation**:
  128. ```typescript
  129. // tests/e2e/retry-resilience.spec.ts
  130. import { test, expect } from '@playwright/test';
  131. /**
  132. * Retry Validation Pattern
  133. * - Force sequential failures (500 → 500 → 200)
  134. * - Validate retry attempts and backoff timing
  135. * - Assert telemetry captures retry events
  136. */
  137. test.describe('Network Retry Logic', () => {
  138. test('should retry on 500 error and succeed', async ({ page }) => {
  139. let attemptCount = 0;
  140. const attemptTimestamps: number[] = [];
  141. // Mock API: Fail twice, succeed on third attempt
  142. await page.route('**/api/products', (route) => {
  143. attemptCount++;
  144. attemptTimestamps.push(Date.now());
  145. if (attemptCount <= 2) {
  146. // First 2 attempts: 500 error
  147. route.fulfill({
  148. status: 500,
  149. body: JSON.stringify({ error: 'Server error' }),
  150. });
  151. } else {
  152. // 3rd attempt: Success
  153. route.fulfill({
  154. status: 200,
  155. contentType: 'application/json',
  156. body: JSON.stringify({ products: [{ id: 1, name: 'Product 1' }] }),
  157. });
  158. }
  159. });
  160. // Act: Navigate (should retry automatically)
  161. await page.goto('/products');
  162. // Assert: Data eventually loads after retries
  163. await expect(page.getByTestId('product-list')).toBeVisible();
  164. await expect(page.getByTestId('product-item')).toHaveCount(1);
  165. // Assert: Exactly 3 attempts made
  166. expect(attemptCount).toBe(3);
  167. // Assert: Exponential backoff timing (1s → 2s between attempts)
  168. if (attemptTimestamps.length === 3) {
  169. const delay1 = attemptTimestamps[1] - attemptTimestamps[0];
  170. const delay2 = attemptTimestamps[2] - attemptTimestamps[1];
  171. expect(delay1).toBeGreaterThanOrEqual(900); // ~1 second
  172. expect(delay1).toBeLessThan(1200);
  173. expect(delay2).toBeGreaterThanOrEqual(1900); // ~2 seconds
  174. expect(delay2).toBeLessThan(2200);
  175. }
  176. // Assert: Telemetry logged retry events
  177. const telemetryEvents = await page.evaluate(() => (window as any).__TELEMETRY_EVENTS__ || []);
  178. expect(telemetryEvents).toContainEqual(
  179. expect.objectContaining({
  180. event: 'api_retry',
  181. attempt: 1,
  182. endpoint: '/api/products',
  183. }),
  184. );
  185. expect(telemetryEvents).toContainEqual(
  186. expect.objectContaining({
  187. event: 'api_retry',
  188. attempt: 2,
  189. }),
  190. );
  191. });
  192. test('should give up after max retries and show error', async ({ page }) => {
  193. let attemptCount = 0;
  194. // Mock API: Always fail (test retry limit)
  195. await page.route('**/api/products', (route) => {
  196. attemptCount++;
  197. route.fulfill({
  198. status: 500,
  199. body: JSON.stringify({ error: 'Persistent server error' }),
  200. });
  201. });
  202. // Act
  203. await page.goto('/products');
  204. // Assert: Max retries reached (3 attempts typical)
  205. expect(attemptCount).toBe(3);
  206. // Assert: Error UI displayed after exhausting retries
  207. await expect(page.getByTestId('error-message')).toBeVisible();
  208. await expect(page.getByTestId('error-message')).toContainText(/unable.*load|failed.*after.*retries/i);
  209. // Assert: Data not displayed
  210. await expect(page.getByTestId('product-list')).not.toBeVisible();
  211. });
  212. test('should NOT retry on 404 (non-retryable error)', async ({ page }) => {
  213. let attemptCount = 0;
  214. // Mock API: 404 error (should NOT retry)
  215. await page.route('**/api/products/999', (route) => {
  216. attemptCount++;
  217. route.fulfill({
  218. status: 404,
  219. body: JSON.stringify({ error: 'Product not found' }),
  220. });
  221. });
  222. await page.goto('/products/999');
  223. // Assert: Only 1 attempt (no retries on 404)
  224. expect(attemptCount).toBe(1);
  225. // Assert: 404 error displayed immediately
  226. await expect(page.getByTestId('not-found-message')).toBeVisible();
  227. });
  228. });
  229. ```
  230. **Cypress with retry interception**:
  231. ```javascript
  232. // cypress/e2e/retry-resilience.cy.ts
  233. describe('Network Retry Logic', () => {
  234. it('should retry on 500 and succeed on 3rd attempt', () => {
  235. let attemptCount = 0;
  236. cy.intercept('GET', '**/api/products', (req) => {
  237. attemptCount++;
  238. if (attemptCount <= 2) {
  239. req.reply({ statusCode: 500, body: { error: 'Server error' } });
  240. } else {
  241. req.reply({ statusCode: 200, body: { products: [{ id: 1, name: 'Product 1' }] } });
  242. }
  243. }).as('getProducts');
  244. cy.visit('/products');
  245. // Wait for final successful request
  246. cy.wait('@getProducts').its('response.statusCode').should('eq', 200);
  247. // Assert: Data loaded
  248. cy.get('[data-cy="product-list"]').should('be.visible');
  249. cy.get('[data-cy="product-item"]').should('have.length', 1);
  250. // Validate retry count
  251. cy.wrap(attemptCount).should('eq', 3);
  252. });
  253. });
  254. ```
  255. **Key Points**:
  256. - **Sequential failures**: Test retry logic with 500 → 500 → 200
  257. - **Backoff timing**: Validate exponential backoff delays
  258. - **Retry limits**: Max attempts enforced (typically 3)
  259. - **Non-retryable errors**: 404s don't trigger retries
  260. - **Telemetry**: Log retry attempts for monitoring
  261. ---
  262. ### Example 3: Telemetry Logging with Context (Sentry Integration)
  263. **Context**: Capture errors with full context for production debugging without exposing secrets.
  264. **Implementation**:
  265. ```typescript
  266. // tests/e2e/telemetry-logging.spec.ts
  267. import { test, expect } from '@playwright/test';
  268. /**
  269. * Telemetry Logging Pattern
  270. * - Log errors with request context
  271. * - Redact sensitive data (tokens, passwords, PII)
  272. * - Integrate with monitoring (Sentry, Datadog)
  273. * - Validate error logging without exposing secrets
  274. */
  275. type ErrorLog = {
  276. level: 'error' | 'warn' | 'info';
  277. message: string;
  278. context?: {
  279. endpoint?: string;
  280. method?: string;
  281. statusCode?: number;
  282. userId?: string;
  283. sessionId?: string;
  284. };
  285. timestamp: string;
  286. };
  287. test.describe('Error Telemetry', () => {
  288. test('should log API errors with context', async ({ page }) => {
  289. const errorLogs: ErrorLog[] = [];
  290. // Capture console errors
  291. page.on('console', (msg) => {
  292. if (msg.type() === 'error') {
  293. try {
  294. const log = JSON.parse(msg.text());
  295. errorLogs.push(log);
  296. } catch {
  297. // Not a structured log, ignore
  298. }
  299. }
  300. });
  301. // Mock failing API
  302. await page.route('**/api/orders', (route) =>
  303. route.fulfill({
  304. status: 500,
  305. body: JSON.stringify({ error: 'Payment processor unavailable' }),
  306. }),
  307. );
  308. // Act: Trigger error
  309. await page.goto('/checkout');
  310. await page.getByTestId('place-order').click();
  311. // Wait for error UI
  312. await expect(page.getByTestId('error-message')).toBeVisible();
  313. // Assert: Error logged with context
  314. expect(errorLogs).toContainEqual(
  315. expect.objectContaining({
  316. level: 'error',
  317. message: expect.stringContaining('API request failed'),
  318. context: expect.objectContaining({
  319. endpoint: '/api/orders',
  320. method: 'POST',
  321. statusCode: 500,
  322. userId: expect.any(String),
  323. }),
  324. }),
  325. );
  326. // Assert: Sensitive data NOT logged
  327. const logString = JSON.stringify(errorLogs);
  328. expect(logString).not.toContain('password');
  329. expect(logString).not.toContain('token');
  330. expect(logString).not.toContain('creditCard');
  331. });
  332. test('should send errors to Sentry with breadcrumbs', async ({ page }) => {
  333. const sentryEvents: any[] = [];
  334. // Mock Sentry SDK
  335. await page.addInitScript(() => {
  336. (window as any).Sentry = {
  337. captureException: (error: Error, context?: any) => {
  338. (window as any).__SENTRY_EVENTS__ = (window as any).__SENTRY_EVENTS__ || [];
  339. (window as any).__SENTRY_EVENTS__.push({
  340. error: error.message,
  341. context,
  342. timestamp: Date.now(),
  343. });
  344. },
  345. addBreadcrumb: (breadcrumb: any) => {
  346. (window as any).__SENTRY_BREADCRUMBS__ = (window as any).__SENTRY_BREADCRUMBS__ || [];
  347. (window as any).__SENTRY_BREADCRUMBS__.push(breadcrumb);
  348. },
  349. };
  350. });
  351. // Mock failing API
  352. await page.route('**/api/users', (route) => route.fulfill({ status: 403, body: { error: 'Forbidden' } }));
  353. // Act
  354. await page.goto('/users');
  355. // Assert: Sentry captured error
  356. const events = await page.evaluate(() => (window as any).__SENTRY_EVENTS__);
  357. expect(events).toHaveLength(1);
  358. expect(events[0]).toMatchObject({
  359. error: expect.stringContaining('403'),
  360. context: expect.objectContaining({
  361. endpoint: '/api/users',
  362. statusCode: 403,
  363. }),
  364. });
  365. // Assert: Breadcrumbs include user actions
  366. const breadcrumbs = await page.evaluate(() => (window as any).__SENTRY_BREADCRUMBS__);
  367. expect(breadcrumbs).toContainEqual(
  368. expect.objectContaining({
  369. category: 'navigation',
  370. message: '/users',
  371. }),
  372. );
  373. });
  374. });
  375. ```
  376. **Cypress with Sentry**:
  377. ```javascript
  378. // cypress/e2e/telemetry-logging.cy.ts
  379. describe('Error Telemetry', () => {
  380. it('should log API errors with redacted sensitive data', () => {
  381. const errorLogs = [];
  382. // Capture console errors
  383. cy.on('window:before:load', (win) => {
  384. cy.stub(win.console, 'error').callsFake((msg) => {
  385. errorLogs.push(msg);
  386. });
  387. });
  388. // Mock failing API
  389. cy.intercept('POST', '**/api/orders', {
  390. statusCode: 500,
  391. body: { error: 'Payment failed' },
  392. });
  393. // Act
  394. cy.visit('/checkout');
  395. cy.get('[data-cy="place-order"]').click();
  396. // Assert: Error logged
  397. cy.wrap(errorLogs).should('have.length.greaterThan', 0);
  398. // Assert: Context included
  399. cy.wrap(errorLogs[0]).should('include', '/api/orders');
  400. // Assert: Secrets redacted
  401. cy.wrap(JSON.stringify(errorLogs)).should('not.contain', 'password');
  402. cy.wrap(JSON.stringify(errorLogs)).should('not.contain', 'creditCard');
  403. });
  404. });
  405. ```
  406. **Error logger utility with redaction**:
  407. ```typescript
  408. // src/utils/error-logger.ts
  409. type ErrorContext = {
  410. endpoint?: string;
  411. method?: string;
  412. statusCode?: number;
  413. userId?: string;
  414. sessionId?: string;
  415. requestPayload?: any;
  416. };
  417. const SENSITIVE_KEYS = ['password', 'token', 'creditCard', 'ssn', 'apiKey'];
  418. /**
  419. * Redact sensitive data from objects
  420. */
  421. function redactSensitiveData(obj: any): any {
  422. if (typeof obj !== 'object' || obj === null) return obj;
  423. const redacted = { ...obj };
  424. for (const key of Object.keys(redacted)) {
  425. if (SENSITIVE_KEYS.some((sensitive) => key.toLowerCase().includes(sensitive))) {
  426. redacted[key] = '[REDACTED]';
  427. } else if (typeof redacted[key] === 'object') {
  428. redacted[key] = redactSensitiveData(redacted[key]);
  429. }
  430. }
  431. return redacted;
  432. }
  433. /**
  434. * Log error with context (Sentry integration)
  435. */
  436. export function logError(error: Error, context?: ErrorContext) {
  437. const safeContext = context ? redactSensitiveData(context) : {};
  438. const errorLog = {
  439. level: 'error' as const,
  440. message: error.message,
  441. stack: error.stack,
  442. context: safeContext,
  443. timestamp: new Date().toISOString(),
  444. };
  445. // Console (development)
  446. console.error(JSON.stringify(errorLog));
  447. // Sentry (production)
  448. if (typeof window !== 'undefined' && (window as any).Sentry) {
  449. (window as any).Sentry.captureException(error, {
  450. contexts: { custom: safeContext },
  451. });
  452. }
  453. }
  454. ```
  455. **Key Points**:
  456. - **Context-rich logging**: Endpoint, method, status, user ID
  457. - **Secret redaction**: Passwords, tokens, PII removed before logging
  458. - **Sentry integration**: Production monitoring with breadcrumbs
  459. - **Structured logs**: JSON format for easy parsing
  460. - **Test validation**: Assert logs contain context but not secrets
  461. ---
  462. ### Example 4: Graceful Degradation Tests (Fallback Behavior)
  463. **Context**: Validate application continues functioning when services are unavailable.
  464. **Implementation**:
  465. ```typescript
  466. // tests/e2e/graceful-degradation.spec.ts
  467. import { test, expect } from '@playwright/test';
  468. /**
  469. * Graceful Degradation Pattern
  470. * - Simulate service unavailability
  471. * - Validate fallback behavior
  472. * - Ensure user experience degrades gracefully
  473. * - Verify telemetry captures degradation events
  474. */
  475. test.describe('Service Unavailability', () => {
  476. test('should display cached data when API is down', async ({ page }) => {
  477. // Arrange: Seed localStorage with cached data
  478. await page.addInitScript(() => {
  479. localStorage.setItem(
  480. 'products_cache',
  481. JSON.stringify({
  482. data: [
  483. { id: 1, name: 'Cached Product 1' },
  484. { id: 2, name: 'Cached Product 2' },
  485. ],
  486. timestamp: Date.now(),
  487. }),
  488. );
  489. });
  490. // Mock API unavailable
  491. await page.route(
  492. '**/api/products',
  493. (route) => route.abort('connectionrefused'), // Simulate server down
  494. );
  495. // Act
  496. await page.goto('/products');
  497. // Assert: Cached data displayed
  498. await expect(page.getByTestId('product-list')).toBeVisible();
  499. await expect(page.getByText('Cached Product 1')).toBeVisible();
  500. // Assert: Stale data warning shown
  501. await expect(page.getByTestId('cache-warning')).toBeVisible();
  502. await expect(page.getByTestId('cache-warning')).toContainText(/showing.*cached|offline.*mode/i);
  503. // Assert: Retry button available
  504. await expect(page.getByTestId('refresh-button')).toBeVisible();
  505. });
  506. test('should show fallback UI when analytics service fails', async ({ page }) => {
  507. // Mock analytics service down (non-critical)
  508. await page.route('**/analytics/track', (route) => route.fulfill({ status: 503, body: 'Service unavailable' }));
  509. // Act: Navigate normally
  510. await page.goto('/dashboard');
  511. // Assert: Page loads successfully (analytics failure doesn't block)
  512. await expect(page.getByTestId('dashboard-content')).toBeVisible();
  513. // Assert: Analytics error logged but not shown to user
  514. const consoleErrors = [];
  515. page.on('console', (msg) => {
  516. if (msg.type() === 'error') consoleErrors.push(msg.text());
  517. });
  518. // Trigger analytics event
  519. await page.getByTestId('track-action-button').click();
  520. // Analytics error logged
  521. expect(consoleErrors).toContainEqual(expect.stringContaining('Analytics service unavailable'));
  522. // But user doesn't see error
  523. await expect(page.getByTestId('error-message')).not.toBeVisible();
  524. });
  525. test('should fallback to local validation when API is slow', async ({ page }) => {
  526. // Mock slow API (> 5 seconds)
  527. await page.route('**/api/validate-email', async (route) => {
  528. await new Promise((resolve) => setTimeout(resolve, 6000)); // 6 second delay
  529. route.fulfill({
  530. status: 200,
  531. body: JSON.stringify({ valid: true }),
  532. });
  533. });
  534. // Act: Fill form
  535. await page.goto('/signup');
  536. await page.getByTestId('email-input').fill('test@example.com');
  537. await page.getByTestId('email-input').blur();
  538. // Assert: Client-side validation triggers immediately (doesn't wait for API)
  539. await expect(page.getByTestId('email-valid-icon')).toBeVisible({ timeout: 1000 });
  540. // Assert: Eventually API validates too (but doesn't block UX)
  541. await expect(page.getByTestId('email-validated-badge')).toBeVisible({ timeout: 7000 });
  542. });
  543. test('should maintain functionality with third-party script failure', async ({ page }) => {
  544. // Block third-party scripts (Google Analytics, Intercom, etc.)
  545. await page.route('**/*.google-analytics.com/**', (route) => route.abort());
  546. await page.route('**/*.intercom.io/**', (route) => route.abort());
  547. // Act
  548. await page.goto('/');
  549. // Assert: App works without third-party scripts
  550. await expect(page.getByTestId('main-content')).toBeVisible();
  551. await expect(page.getByTestId('nav-menu')).toBeVisible();
  552. // Assert: Core functionality intact
  553. await page.getByTestId('nav-products').click();
  554. await expect(page).toHaveURL(/.*\/products/);
  555. });
  556. });
  557. ```
  558. **Key Points**:
  559. - **Cached fallbacks**: Display stale data when API unavailable
  560. - **Non-critical degradation**: Analytics failures don't block app
  561. - **Client-side fallbacks**: Local validation when API slow
  562. - **Third-party resilience**: App works without external scripts
  563. - **User transparency**: Stale data warnings displayed
  564. ---
  565. ## Error Handling Testing Checklist
  566. Before shipping error handling code, verify:
  567. - [ ] **Scoped exception handling**: Only ignore documented errors (NetworkError, specific codes)
  568. - [ ] **Rethrow unexpected**: Unknown errors fail tests (catch regressions)
  569. - [ ] **Error UI tested**: User sees error messages for all error states
  570. - [ ] **Retry logic validated**: Sequential failures test backoff and max attempts
  571. - [ ] **Telemetry verified**: Errors logged with context (endpoint, status, user)
  572. - [ ] **Secret redaction**: Logs don't contain passwords, tokens, PII
  573. - [ ] **Graceful degradation**: Critical services down, app shows fallback UI
  574. - [ ] **Non-critical failures**: Analytics/tracking failures don't block app
  575. ## Integration Points
  576. - Used in workflows: `*automate` (error handling test generation), `*test-review` (error pattern detection)
  577. - Related fragments: `network-first.md`, `test-quality.md`, `contract-testing.md`
  578. - Monitoring tools: Sentry, Datadog, LogRocket
  579. _Source: Murat error-handling patterns, Pact resilience guidance, enterprise production error handling_