Svelte Exception Handling: Stop Apps from Freezing
In this article
To avoid exceptions from freezing your entire Svelte application, you must implement a combination of try-catch blocks for asynchronous logic and Error Boundaries (via custom components or SvelteKit's built-in error pages) to isolate failures to specific UI sections. By capturing errors at the component level, you prevent a single JavaScript crash from bubbling up to the root of the DOM and halting the entire reactive cycle of the app.
What You'll Need
- A Svelte or SvelteKit project environment.
- Basic familiarity with JavaScript async/await patterns.
- A development browser with Console tools open for debugging.
Step-by-Step
- Wrap Asynchronous Calls in Try-Catch Blocks: Most app freezes occur during API fetches or timeouts. Never leave a promise unhandled. Wrap your data fetching logic in a try-catch block to ensure that if a network request fails, the app remains interactive. Create a local state variable (e.g.,
let error = null;) to store the error message and display it to the user instead of letting the exception crash the script execution. - Implement a Component-Level Error Boundary: Svelte does not have a built-in <ErrorBoundary> component like React, so you must create a wrapper pattern. Create a wrapper component that uses a boolean flag to track if a child has crashed. Use the
{#if !hasError}block to render the content. If an error is caught in the child's logic, update the parent's state to show a fallback UI. This prevents a crash in a small widget from breaking the navigation bar or other critical global elements. - Utilize SvelteKit's
+error.sveltePages: If you are using SvelteKit, leverage the file-system based error handling. Create a+error.sveltefile in your route directory. When a load function throws an error or a server-side exception occurs, SvelteKit will automatically render this page instead of a blank white screen. This ensures the user can still use the browser's back button or a "Return Home" link provided in your error template. - Sanitize External Data Inputs: Many exceptions are caused by attempting to access properties of
undefinedornull(the dreaded "Cannot read property of undefined"). Before rendering data in your HTML templates, use optional chaining (data?.user?.name) or provide default values. This prevents the Svelte compiler's reactive updates from triggering a runtime exception that could lock the UI thread. - Handle Global Uncaught Exceptions: For errors that slip through component-level guards, add a global listener in your
main.jsor__root.svelte. Usewindow.addEventListener('error', ... )andwindow.addEventListener('unhandledrejection', ... ). Instead of letting these crash the app, use these listeners to log the error to a monitoring service and trigger a graceful notification to the user, suggesting a page refresh. - Offload Heavy Computation to Web Workers: If your app freezes because of a long-running loop or heavy data processing (which looks like an exception/hang), move that logic into a Web Worker. This moves the execution off the main UI thread, meaning even if the worker encounters a fatal error or enters an infinite loop, the Svelte UI remains responsive and the user can still click buttons or navigate away.
Common Mistakes
One of the most frequent mistakes is placing the try-catch block inside a Svelte reactive statement ($: { ... }) without a way to reset the error state. If the reactive statement triggers again and fails, the app may enter a rapid loop of crashing and re-rendering, which effectively freezes the browser tab. Always ensure your error state is cleared or handled before the reactive dependency is updated again.
Another common error is over-reliance on global error handlers. While window.onerror is a good safety net, relying on it as your primary strategy is dangerous because it doesn't provide the context needed to recover specific parts of the UI. By the time a global handler catches an error, the internal state of your Svelte components may already be corrupted, making a partial recovery impossible.
Developers also often forget to handle the "loading" state alongside the "error" state. If an exception occurs during a fetch and the loading spinner is never toggled off, the user perceives the app as frozen, even if the JavaScript engine is technically still running. Always use a finally block to set loading = false regardless of whether the operation succeeded or failed.
Tips
Use TypeScript to catch potential "undefined" exceptions during development. By defining strict interfaces for your API responses, the compiler will force you to handle cases where data might be missing, eliminating a huge percentage of the runtime exceptions that lead to app freezes.
Implement a "Circuit Breaker" pattern for unstable API endpoints. If a specific component fails three times in a row, stop attempting to load that component for a set period. This prevents the app from constantly attempting a failing operation that might be consuming excessive memory or CPU, which can lead to perceived freezes.
When designing fallback UIs, keep them extremely simple. Avoid putting complex logic or further API calls inside your error components. If the error component itself throws an exception, you will likely encounter a recursive crash that will definitively freeze the browser window.
Troubleshooting
If your app is still freezing despite having try-catch blocks, first check the browser's Developer Tools Console. Look for "Maximum call stack size exceeded" errors. This indicates an infinite loop (often in a reactive $: statement) rather than a standard exception. To fix this, trace which variable is triggering the update and ensure it isn't being modified by the same statement that reads it.
If the screen is white and no errors appear in the console, check your SvelteKit +layout.svelte. An error in a root layout can prevent all child pages from rendering. Try moving your error handling logic higher up the component tree or checking the server-side logs if you are using Server Side Rendering (SSR), as the exception might be happening on the server before the HTML ever reaches the browser.
If the UI is unresponsive but the console is quiet, check for memory leaks. Use the Memory tab in Chrome DevTools to see if a specific object is growing indefinitely. Large arrays being updated reactively in Svelte can cause the DOM reconciliation process to take seconds or minutes, which mimics a freeze. In this case, use svelte-virtual-list or pagination to reduce the number of DOM elements.
Frequently Asked Questions
Does Svelte have a built-in Error Boundary component?
No, Svelte does not have a native <ErrorBoundary> component like React. You must implement this manually using a wrapper component with a try-catch mechanism or by utilizing SvelteKit's +error.svelte pages for route-level failures.
Will a try-catch block stop a Svelte reactive statement from crashing?
Yes, if you wrap the logic inside the $: { ... } block in a try-catch, the exception will be caught and will not propagate to the global scope, preventing the rest of the app from freezing.
What is the difference between a JS exception and a Svelte app freeze?
An exception is a specific error in the code (like calling a method on null). A freeze happens when the main thread is blocked, either by a fatal unhandled exception that stops the JS engine or by an infinite loop/heavy computation that prevents the browser from painting the UI.
Can SvelteKit handle server-side exceptions without crashing the client?
Yes. SvelteKit is designed to catch errors in load functions and render the nearest +error.svelte page. This keeps the client-side application shell intact while showing an error message for the specific failing route.
How do I prevent "Cannot read property of undefined" in Svelte templates?
The most effective way is using optional chaining (?.) in your HTML expressions. For example, {user?.profile?.name} will simply render nothing if the user or profile is missing, rather than throwing an exception that could crash the component.