automerge-repo icon indicating copy to clipboard operation
automerge-repo copied to clipboard

Add InvalidAutomergeUrlError

Open neftaly opened this issue 1 year ago • 3 comments

This PR exports a custom error for invalid automerge URLs, as per #268. The intention is to allow error instanceof InvalidAutomergeUrlError to be used in try/catch blocks and react error boundaries.

For example:

import { InvalidAutomergeUrlError } from 'automerge-repo'
import { ErrorBoundary } from 'react-error-boundary'

export const Bootstrap = () => {
  const handle = useBootstrap({
    onNoDocument: (repo) => {
      const handle = repo.create()
      handle.change((d) => Object.assign(d, { foo: {} }))
      return handle
    }
  })

  const [state] = useDocument(handle?.url)
  if (!state) return (<LoadingDocument />)

  return <Client automergeUrl={handle?.url} />
}

export const ErrorFallback = ({ error }) => {
  if (error instanceof InvalidAutomergeUrlError) {
    return (<p>Invalid document URL</p>)
  }
  return (<p>{error.message}</p>)
}

export const App = () => {
  return (
    <ErrorBoundary FallbackComponent={ErrorFallback}>
      <Bootstrap />
    </ErrorBoundary>
  )
}

neftaly avatar Jan 23 '24 23:01 neftaly