Просмотр исходного кода

Show a lost connection as a lost connection, not as a server error (#665)

* Show a lost connection as one instead of the 500 page

* Recognise a lost connection reported from another frame
Bernt Christian Egeland 5 дней назад
Родитель
Сommit
66c4fc76f6

+ 53 - 0
src/__tests__/app/error-page.test.tsx

@@ -54,4 +54,57 @@ describe('error page', () => {
     render(<ErrorPage error={error} />)
     render(<ErrorPage error={error} />)
     expect(reportError).toHaveBeenCalledWith(error, { error_page: 'page', digest: null })
     expect(reportError).toHaveBeenCalledWith(error, { error_page: 'page', digest: null })
   })
   })
+
+  it('shows the 500 page for a real error that mentions the network', () => {
+    render(<ErrorPage error={new TypeError('Network error while saving the invoice')} />)
+    expect(screen.getByText('500')).toBeInTheDocument()
+    expect(screen.queryByText("Couldn't reach Torqvoice")).not.toBeInTheDocument()
+    expect(reportError).toHaveBeenCalledTimes(1)
+  })
+})
+
+describe('error page for a lost connection', () => {
+  // Chrome's words when a response stops arriving midway
+  const cut = () => new TypeError('network error')
+
+  it('says the connection was lost instead of showing the 500 page', () => {
+    render(<ErrorPage error={cut()} reset={vi.fn()} />)
+    expect(screen.getByRole('heading', { name: "Couldn't reach Torqvoice" })).toBeInTheDocument()
+    expect(
+      screen.getByText(
+        'Your last change may not have been saved. Check your connection and try again.'
+      )
+    ).toBeInTheDocument()
+    expect(screen.queryByText('500')).not.toBeInTheDocument()
+    expect(screen.queryByText('Something Went Wrong')).not.toBeInTheDocument()
+  })
+
+  it('draws the page again in place on Try again, without a reload', () => {
+    const reset = vi.fn()
+    render(<ErrorPage error={cut()} reset={reset} />)
+    fireEvent.click(screen.getByRole('button', { name: /try again/i }))
+    expect(reset).toHaveBeenCalledTimes(1)
+    expect(reload).not.toHaveBeenCalled()
+  })
+
+  it("prefers Next's retry, which also fetches the page again", () => {
+    const reset = vi.fn()
+    const retry = vi.fn()
+    render(<ErrorPage error={cut()} reset={reset} retry={retry} />)
+    fireEvent.click(screen.getByRole('button', { name: /try again/i }))
+    expect(retry).toHaveBeenCalledTimes(1)
+    expect(reset).not.toHaveBeenCalled()
+  })
+
+  it('reloads when there is nothing to reset', () => {
+    render(<ErrorPage error={cut()} />)
+    fireEvent.click(screen.getByRole('button', { name: /try again/i }))
+    expect(reload).toHaveBeenCalledTimes(1)
+  })
+
+  it('is not reported as a crash', () => {
+    vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+    render(<ErrorPage error={new TypeError('Failed to fetch')} reset={vi.fn()} />)
+    expect(reportError).not.toHaveBeenCalled()
+  })
 })
 })

+ 49 - 0
src/__tests__/lib/network-error.test.ts

@@ -0,0 +1,49 @@
+import { runInNewContext } from 'node:vm'
+import { describe, expect, it } from 'vitest'
+import { isNetworkError } from '@/lib/network-error'
+
+/**
+ * A lost connection gets the calm connection notice, never the 500 page, so
+ * each browser's words for it must be recognised, and nothing else.
+ */
+describe('isNetworkError', () => {
+  it.each([
+    ['Chrome, no answer', 'Failed to fetch'],
+    ['Chrome, no answer, with the host', 'Failed to fetch (app.torqvoice.com)'],
+    ['Chrome, response cut off midway', 'network error'],
+    ['Firefox', 'NetworkError when attempting to fetch resource.'],
+    ['Safari', 'Load failed'],
+    ['Safari, dropped mid-request', 'The network connection was lost.'],
+    ['older Safari, offline', 'The Internet connection appears to be offline.'],
+  ])('recognises %s: "%s"', (_browser, message) => {
+    expect(isNetworkError(new TypeError(message))).toBe(true)
+  })
+
+  it('recognises a TypeError made in another realm', () => {
+    // What an error thrown inside another frame is: neither this realm's
+    // TypeError nor its Error.
+    const foreign = runInNewContext('new TypeError("network error")')
+    expect(foreign instanceof TypeError).toBe(false)
+    expect(foreign instanceof Error).toBe(false)
+    expect(isNetworkError(foreign)).toBe(true)
+    expect(isNetworkError(runInNewContext('new Error("network error")'))).toBe(false)
+  })
+
+  it.each([
+    'Network error while saving the invoice',
+    'network error: invoice number already taken',
+    'Could not sync: network error',
+    'Failed to fetch dynamically imported module: https://app.torqvoice.com/_next/static/chunks/a.js',
+    "Cannot read properties of undefined (reading 'id')",
+  ])('leaves an application error alone: "%s"', (message) => {
+    expect(isNetworkError(new TypeError(message))).toBe(false)
+  })
+
+  it('only counts what fetch throws, not an Error or a string with the same words', () => {
+    expect(isNetworkError(new Error('network error'))).toBe(false)
+    expect(isNetworkError(new Error('Failed to fetch'))).toBe(false)
+    expect(isNetworkError('network error')).toBe(false)
+    expect(isNetworkError(null)).toBe(false)
+    expect(isNetworkError({ name: 'TypeError', message: 'network error' })).toBe(false)
+  })
+})

+ 50 - 3
src/app/error.tsx

@@ -2,19 +2,37 @@
 
 
 import { useEffect } from 'react'
 import { useEffect } from 'react'
 import { useTranslations } from 'next-intl'
 import { useTranslations } from 'next-intl'
-import { Wrench } from 'lucide-react'
+import { WifiOff, Wrench } from 'lucide-react'
 import { Button } from '@/components/ui/button'
 import { Button } from '@/components/ui/button'
 import { reportError } from '@/lib/analytics'
 import { reportError } from '@/lib/analytics'
+import { isNetworkError } from '@/lib/network-error'
+
+interface ErrorPageProps {
+  error: Error & { digest?: string }
+  reset?: () => void
+  /** Next's reset that also fetches the page from the server again. */
+  retry?: () => void
+}
 
 
 // biome-ignore lint/suspicious/noShadowRestrictedNames: Next.js error boundary convention
 // biome-ignore lint/suspicious/noShadowRestrictedNames: Next.js error boundary convention
-export default function Error({ error }: { error: Error & { digest?: string } }) {
+export default function Error({ error, reset, retry }: ErrorPageProps) {
   const t = useTranslations('common')
   const t = useTranslations('common')
+  const lostConnection = isNetworkError(error)
 
 
   useEffect(() => {
   useEffect(() => {
+    // A dropped connection is the network, not a crash: nothing to report
+    if (lostConnection) {
+      console.warn(error)
+      return
+    }
     console.error(error)
     console.error(error)
     // The digest finds the error in the server log when the server threw it
     // The digest finds the error in the server log when the server threw it
     reportError(error, { error_page: 'page', digest: error.digest ?? null })
     reportError(error, { error_page: 'page', digest: error.digest ?? null })
-  }, [error])
+  }, [error, lostConnection])
+
+  if (lostConnection) {
+    return <ConnectionLost onRetry={retry ?? reset ?? (() => window.location.reload())} />
+  }
 
 
   return (
   return (
     <div className="grid-bg flex min-h-screen items-center justify-center p-4">
     <div className="grid-bg flex min-h-screen items-center justify-center p-4">
@@ -49,3 +67,32 @@ export default function Error({ error }: { error: Error & { digest?: string } })
     </div>
     </div>
   )
   )
 }
 }
+
+/**
+ * Shown instead of the 500 page when the page broke because the connection
+ * dropped, in the words and look of the connection notice. Try again draws
+ * the page again in place, which works once the connection is back; nothing
+ * in the tab is wrong, so a reload is not needed.
+ */
+function ConnectionLost({ onRetry }: { onRetry: () => void }) {
+  const t = useTranslations('common')
+
+  return (
+    <div className="grid-bg flex min-h-screen items-center justify-center p-4">
+      <div className="glass relative w-full max-w-md overflow-hidden rounded-2xl p-8 text-center shadow-2xl">
+        <div
+          aria-hidden
+          className="pointer-events-none absolute inset-x-0 top-0 h-px bg-linear-to-r from-transparent via-primary to-transparent"
+        />
+        <div className="mb-6 inline-flex h-16 w-16 items-center justify-center rounded-2xl bg-linear-to-b from-primary/15 to-primary/5 text-primary shadow-[inset_0_1px_0_rgb(255_255_255/0.15)] ring-1 ring-primary/25 ring-inset">
+          <WifiOff className="h-7 w-7" strokeWidth={1.75} aria-hidden />
+        </div>
+        <h1 className="text-xl font-semibold tracking-tight">{t('connectionLost.title')}</h1>
+        <p className="mt-2 text-sm text-muted-foreground">{t('connectionLost.description')}</p>
+        <div className="mt-8 flex justify-center">
+          <Button onClick={onRetry}>{t('errorPage.tryAgain')}</Button>
+        </div>
+      </div>
+    </div>
+  )
+}

+ 158 - 3
src/app/global-error.tsx

@@ -1,14 +1,35 @@
 'use client'
 'use client'
 
 
-import { useEffect } from 'react'
+import { useEffect, useState } from 'react'
 import { reportError } from '@/lib/analytics'
 import { reportError } from '@/lib/analytics'
+import { isNetworkError } from '@/lib/network-error'
+
+export default function GlobalError({
+  error,
+  reset,
+  retry,
+}: {
+  error: Error & { digest?: string }
+  reset?: () => void
+  /** Next's reset that also fetches the page from the server again. */
+  retry?: () => void
+}) {
+  const lostConnection = isNetworkError(error)
 
 
-export default function GlobalError({ error }: { error: Error & { digest?: string } }) {
   useEffect(() => {
   useEffect(() => {
+    // A dropped connection is the network, not a crash: nothing to report
+    if (lostConnection) {
+      console.warn(error)
+      return
+    }
     console.error(error)
     console.error(error)
     // Sent only if PostHog started before the root layout broke
     // Sent only if PostHog started before the root layout broke
     reportError(error, { error_page: 'root', digest: error.digest ?? null })
     reportError(error, { error_page: 'root', digest: error.digest ?? null })
-  }, [error])
+  }, [error, lostConnection])
+
+  if (lostConnection) {
+    return <ConnectionLost onRetry={retry ?? reset ?? (() => window.location.reload())} />
+  }
 
 
   return (
   return (
     <html lang="en">
     <html lang="en">
@@ -87,3 +108,137 @@ export default function GlobalError({ error }: { error: Error & { digest?: strin
     </html>
     </html>
   )
   )
 }
 }
+
+/** The themes in src/lib/themes.ts that are light, as the root layout maps them. */
+const LIGHT_THEMES = ['light', 'graphite', 'ocean', 'forest']
+
+/**
+ * Shown instead of the 500 page when the page broke because the connection
+ * dropped. This page is drawn outside the providers and the app's styles, so
+ * it carries its own: the words of the connection notice in English, as the
+ * rest of this page is, and the person's light or dark theme. Try again
+ * draws the page again in place once the connection is back.
+ */
+function ConnectionLost({ onRetry }: { onRetry: () => void }) {
+  const [light, setLight] = useState(false)
+
+  useEffect(() => {
+    try {
+      const theme = localStorage.getItem('torqvoice-theme') ?? 'dark'
+      setLight(
+        theme === 'system'
+          ? !window.matchMedia('(prefers-color-scheme: dark)').matches
+          : LIGHT_THEMES.includes(theme)
+      )
+    } catch {
+      // Storage blocked: the app's default, dark
+    }
+  }, [])
+
+  const c = light
+    ? {
+        bg: '#fafafa',
+        fg: '#09090b',
+        muted: '#71717a',
+        card: '#ffffff',
+        border: 'rgba(0,0,0,0.08)',
+      }
+    : {
+        bg: '#09090b',
+        fg: '#fafafa',
+        muted: '#a1a1aa',
+        card: 'rgba(255,255,255,0.03)',
+        border: 'rgba(255,255,255,0.1)',
+      }
+
+  return (
+    <html lang="en">
+      <body
+        style={{
+          margin: 0,
+          minHeight: '100vh',
+          display: 'flex',
+          alignItems: 'center',
+          justifyContent: 'center',
+          padding: 16,
+          boxSizing: 'border-box',
+          fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
+          background: c.bg,
+          color: c.fg,
+        }}
+      >
+        <div
+          style={{
+            textAlign: 'center',
+            width: '100%',
+            maxWidth: 420,
+            padding: 32,
+            boxSizing: 'border-box',
+            border: `1px solid ${c.border}`,
+            borderRadius: 16,
+            background: c.card,
+            boxShadow: '0 25px 50px -12px rgba(0,0,0,0.25)',
+          }}
+        >
+          <div
+            style={{
+              display: 'inline-flex',
+              alignItems: 'center',
+              justifyContent: 'center',
+              width: 64,
+              height: 64,
+              marginBottom: 24,
+              borderRadius: 16,
+              border: `1px solid ${c.border}`,
+            }}
+          >
+            {/* lucide wifi-off, the icon of the connection notice */}
+            <svg
+              xmlns="http://www.w3.org/2000/svg"
+              width="28"
+              height="28"
+              viewBox="0 0 24 24"
+              fill="none"
+              stroke="currentColor"
+              strokeWidth="1.75"
+              strokeLinecap="round"
+              strokeLinejoin="round"
+              aria-hidden="true"
+              style={{ display: 'block' }}
+            >
+              <path d="M12 20h.01" />
+              <path d="M8.5 16.429a5 5 0 0 1 7 0" />
+              <path d="M5 12.859a10 10 0 0 1 5.17-2.69" />
+              <path d="M19 12.859a10 10 0 0 0-2.007-1.523" />
+              <path d="M2 8.82a15 15 0 0 1 4.177-2.643" />
+              <path d="M22 8.82a15 15 0 0 0-11.288-3.764" />
+              <path d="m2 2 20 20" />
+            </svg>
+          </div>
+          <h1 style={{ fontSize: 20, fontWeight: 600, margin: '0 0 8px' }}>
+            Couldn&apos;t reach Torqvoice
+          </h1>
+          <p style={{ fontSize: 14, lineHeight: 1.5, color: c.muted, margin: '0 0 32px' }}>
+            Your last change may not have been saved. Check your connection and try again.
+          </p>
+          <button
+            type="button"
+            onClick={onRetry}
+            style={{
+              padding: '10px 24px',
+              fontSize: 14,
+              fontWeight: 500,
+              color: c.bg,
+              background: c.fg,
+              border: 'none',
+              borderRadius: 8,
+              cursor: 'pointer',
+            }}
+          >
+            Try Again
+          </button>
+        </div>
+      </body>
+    </html>
+  )
+}

+ 2 - 17
src/components/connection-watcher.tsx

@@ -4,6 +4,7 @@ import { useTranslations } from 'next-intl'
 import { useEffect } from 'react'
 import { useEffect } from 'react'
 import { WifiOff } from 'lucide-react'
 import { WifiOff } from 'lucide-react'
 import { showNotice } from '@/components/notice-toast'
 import { showNotice } from '@/components/notice-toast'
+import { isNetworkError } from '@/lib/network-error'
 
 
 const TOAST_ID = 'connection-lost'
 const TOAST_ID = 'connection-lost'
 
 
@@ -16,23 +17,7 @@ const TOAST_ID = 'connection-lost'
  */
  */
 export const RECENT_INPUT_MS = 60 * 1000
 export const RECENT_INPUT_MS = 60 * 1000
 
 
-/**
- * What each browser's fetch throws when the request never reached the
- * server: offline, a dropped connection, a network change. Chrome, Firefox
- * and Safari (old and new) word it differently.
- */
-const NETWORK_ERROR_MESSAGES = [
-  /^Failed to fetch/,
-  /^NetworkError when attempting to fetch resource/,
-  /^Load failed$/,
-  /^The network connection was lost/,
-  /^The Internet connection appears to be offline/,
-]
-
-export function isNetworkError(error: unknown): boolean {
-  if (!(error instanceof TypeError)) return false
-  return NETWORK_ERROR_MESSAGES.some((pattern) => pattern.test(error.message))
-}
+export { isNetworkError }
 
 
 /**
 /**
  * Says so when something the person just did did not reach the server.
  * Says so when something the person just did did not reach the server.

+ 35 - 0
src/lib/network-error.ts

@@ -0,0 +1,35 @@
+/**
+ * What each browser's fetch throws when the connection is gone: offline, a
+ * dropped connection, a network change, or a response cut off halfway.
+ * Chrome, Firefox and Safari (old and new) word it differently. Matched
+ * whole, so an application error that merely mentions the network still
+ * shows as the error it is.
+ */
+const NETWORK_ERROR_MESSAGES = [
+  // Chrome and Edge, for a request that never got an answer. Newer Chrome
+  // may add the host in brackets
+  /^Failed to fetch( \(.+\))?$/,
+  // Chrome and Edge, for a response whose body stopped arriving midway
+  /^network error$/,
+  // Firefox
+  /^NetworkError when attempting to fetch resource\.?$/,
+  // Safari
+  /^Load failed$/,
+  /^The network connection was lost\.?$/,
+  /^The Internet connection appears to be offline\.?$/,
+]
+
+/**
+ * Whether an error means the browser lost its connection to the server,
+ * rather than that something in the app broke. Shared by the connection
+ * notice and the error pages, so both draw the line in the same place.
+ */
+export function isNetworkError(error: unknown): boolean {
+  // By what it is, not by which window made it: an error thrown in another
+  // frame or realm is an instance of neither this window's TypeError nor its
+  // Error, but it still says what it is.
+  if (Object.prototype.toString.call(error) !== '[object Error]') return false
+  const { name, message } = error as { name?: unknown; message?: unknown }
+  if (name !== 'TypeError' || typeof message !== 'string') return false
+  return NETWORK_ERROR_MESSAGES.some((pattern) => pattern.test(message))
+}