JavaScript Error Handling That Actually Works

Stop ignoring errors. Learn structured error handling patterns for JavaScript and TypeScript including custom errors, boundaries, and async patterns.

· 3 min read

Yellow and black road sign
In this article7 sections
  1. The Cost of Ignoring Errors
  2. The Error Object
  3. Custom Error Classes
  4. Try-Catch Patterns
  5. React Error Boundaries
  6. Global Error Handling
  7. Logging Strategy

The Cost of Ignoring Errors

Every application has bugs. The difference between a frustrating app and a reliable one is not the absence of errors but how gracefully they are handled. Too many JavaScript developers rely on console.log and hope for the best. Let us fix that.

The Error Object

JavaScript's built-in Error class contains three useful properties: name, message, and stack. The stack trace is invaluable for debugging but should never be exposed to end users in production.

Always throw Error objects, never strings. Throwing a string loses the stack trace and makes debugging significantly harder. Use: throw new Error("Something went wrong") instead of throw "Something went wrong".

Custom Error Classes

Create specific error classes for different failure modes:

class ValidationError extends Error with a constructor that takes a field name and message, setting this.name to 'ValidationError' and storing the field.

class NetworkError extends Error with properties for status code and response body.

class AuthenticationError extends Error for auth-specific failures.

This lets calling code handle different errors differently with instanceof checks instead of parsing error message strings.

Try-Catch Patterns

The Minimum Viable Pattern

Always catch errors at meaningful boundaries: API call handlers, event handlers, and async operation wrappers. Do not wrap every single line in try-catch.

Async/Await Error Handling

With async/await, use try-catch blocks around groups of related async operations. For promise chains, use .catch() at the end. Never leave a promise without error handling because unhandled promise rejections will crash Node.js and show cryptic errors in browsers.

Error Recovery vs Error Reporting

Decide for each error whether you can recover from it or just need to report it. A network timeout might be recoverable with a retry. A validation error should be shown to the user. A database corruption error should be logged and escalated.

React Error Boundaries

Error boundaries catch JavaScript errors in the component tree below them and display a fallback UI instead of crashing the entire application. Every React app should have at least one error boundary wrapping the main content.

Create error boundaries at logical divisions in your app: one around the main content, one around the sidebar, one around each independent widget. This way, a crash in the chat widget does not take down the entire page.

Global Error Handling

Set up window.onerror and window.onunhandledrejection handlers to catch errors that escape your try-catch blocks. Send these to an error tracking service like Sentry or LogRocket so you know about production errors before your users report them.

Logging Strategy

Use structured logging with consistent fields: timestamp, error level, error name, message, stack trace, user context, and request ID. This makes errors searchable and filterable in your logging system. Never log sensitive data like passwords, tokens, or personal information.

  • JavaScript
  • Error Handling
  • TypeScript

Written by Pontus Henriksson

Co-founder and CEO of Walldy in Sundsvall. I have built for the web since I was fourteen, tested games for studios like Netflix and Bungie since 2021, and write about what I use in real projects.

Liked this? Get the next one.

New Claude skills, kits and what I learn building AI for small businesses. Not often, only when it is worth sending. Unsubscribe with one click.

Tools for this.

Claude skills, kits and guides that put ideas like these to work. Many are free with an account.

Visit the shop