sajad torkamani

Create a registerRuntimeErrorListener function:

export function registerRuntimeErrorListener() {
  function showErrorOverlay(error: ErrorPayload['err']) {
    const ErrorOverlay = customElements.get('vite-error-overlay')

    if (!ErrorOverlay) {
      return
    }

    console.error(error)
    const overlay = new ErrorOverlay(error)
    document.body.appendChild(overlay)
  }

  window.addEventListener('error', ({ error }) => showErrorOverlay(error))
  window.addEventListener('unhandledrejection', ({ reason }) =>
    showErrorOverlay(reason),
  )
}

Call that function in an entry file (e.g., src/main.tsx):

Now, try doing something that triggers a runtime error like using a non-existing component named <BackLink /> and you should see the error in your browser:

How to show error overlay for Vite runtime errors

Sources/links

Tagged: Vite

Leave a comment

Your email address will not be published. Required fields are marked *