Error Handling and Debugging in the Browser

Use try/catch and custom errors, handle asynchronous failures, read stack traces, and debug with browser DevTools.

Est. 35 min Updated Suggest a fix
// Part 01 — Why failures matter

An Error Is Information, Not a Surprise

A user clicks Pay, the browser sends a request, and the connection drops. Or a saved value is malformed, a required element is missing, or a function receives an unexpected input. These are normal failure conditions, not reasons to hide the problem or leave the interface stuck. Good error handling makes failures visible to the right audience and gives the application a safe next step.

JavaScript errors have a name, a message, and usually a stack trace showing where the error was created and how the code reached it. Read the first useful application frame in that trace; do not assume the last line in a minified bundle is the cause. During development, preserve details. In the UI, show a clear, non-technical explanation and a recovery action where one exists.

Classifying the failure helps decide whether to recover, report, or fix code.
Failure categoryExampleFirst response
Programmer errorReading a property from undefinedReproduce, inspect inputs and fix the faulty assumption
Invalid user inputAn amount is blank or not positiveValidate at the boundary and explain how to correct it
Expected operational failureNetwork is unavailable or a record is missingHandle it explicitly and offer retry or a useful alternative
Unexpected external dataA response is not valid JSONCheck the response shape before using it
💡 Note
An error message is not a user interface. Keep diagnostic detail for developers and logs; present users with the information they need to continue without exposing stack traces, internal paths, or private data.
// Part 02 — Throwing and catching

Catch Only Where You Can Make a Decision

A thrown value interrupts the current synchronous path until a matching catch handles it. JavaScript code should throw Error objects rather than strings: errors include a useful stack trace and can carry a descriptive name. Use try / catch around work that is expected to fail, then recover, translate the error, or rethrow it. A catch that merely logs and returns a fake success makes later bugs harder to find.

amount.js
javascript
function parseAmount(rawValue) {
  const amount = Number(rawValue)
  if (!Number.isFinite(amount) || amount <= 0) {
    throw new TypeError('Amount must be a positive number')
  }
  return amount
}

try {
  const amount = parseAmount('')
  console.log('Amount:', amount)
} catch (error) {
  if (error instanceof Error) {
    console.error('Could not parse amount:', error.message)
  }
}

The example checks the parsed number, not just whether the string is non-empty: Number('') is zero. Validate at the boundary where untrusted input enters your program, and keep the validation rule close to the domain it protects. Avoid a broad catch around unrelated code because it obscures which operation actually failed.

🎯 Pro Tip
Catch an error only when you can add context, recover, or convert it into a result the caller understands. Otherwise, let it propagate to a layer that can make that decision.
// Part 03 — Domain errors

Give Expected Failures a Clear Meaning

A domain-specific error tells callers what went wrong without making them inspect fragile message text. Extend Error, set the class name, and keep sensitive values out of the message. Callers can then distinguish a missing expense from an unexpected programming defect and decide whether to show a not-found state or report a bug.

errors.js
javascript
class ExpenseNotFoundError extends Error {
  constructor(expenseId) {
    super('Expense was not found')
    this.name = 'ExpenseNotFoundError'
    this.expenseId = expenseId
  }
}

function findExpense(expenses, id) {
  const expense = expenses.find((item) => item.id === id)
  if (!expense) {
    throw new ExpenseNotFoundError(id)
  }
  return expense
}

try {
  const expense = findExpense([], 'exp-42')
  console.log(expense.description)
} catch (error) {
  if (error instanceof ExpenseNotFoundError) {
    console.info('Show the not-found state for:', error.expenseId)
  } else {
    throw error
  }
}

Do not turn every possible problem into a custom class. A few stable error types at meaningful boundaries are easier to maintain than a large hierarchy. If you wrap a lower-level error, preserve it as a cause when your runtime and project conventions support it; the original failure is often essential for debugging.

// Part 04 — Async failures

Handle Rejected Promises at the Await Point

A synchronous try / catch does not catch a promise rejection unless that promise is awaited inside the try. A function marked async returns a promise; rejected work becomes a rejected promise too. Put the request and its parsing in the protected block, check HTTP status explicitly, and let the caller decide how the screen should recover.

courses.js
javascript
async function loadCourses() {
  const response = await fetch('/api/courses')
  if (!response.ok) {
    throw new Error('Course request failed with status ' + response.status)
  }
  return response.json()
}

async function showCourses() {
  try {
    const courses = await loadCourses()
    renderCourses(courses)
  } catch (error) {
    console.error('Could not load courses:', error)
    showMessage('Courses could not be loaded. Check your connection and try again.')
  }
}

This handles fetch rejection and non-success HTTP responses; fetch does not reject just because a server returned a 404 or 500. In a real component, also represent loading and error state so a failed refresh does not leave a spinner running forever. Do not retry every failure automatically: a malformed request will not improve by repeating it.

⚠️ Important
Every promise needs an owner for rejection handling. An un-awaited request launched from a click handler can become an unhandled rejection. Await it in an async handler or attach a deliberate rejection handler.
// Part 05 — Debugging workflow

Reproduce, Inspect, Change One Thing

A disciplined debugging loop is faster than random edits. Record what you expected, what happened, and the smallest set of steps that reproduces it. Then inspect inputs and state at the first incorrect point. A breakpoint pauses execution so you can examine local variables, call stack, and the next statement without adding temporary logs everywhere.

DevTools areaUse it to answerUseful habit
ConsoleWhat error or unexpected value appeared?Read the complete stack and inspect the first app-owned frame
Sources / debuggerWhat values led to this branch?Pause on an exception or set a breakpoint before the bad state
NetworkDid the request leave, and what came back?Inspect URL, method, status, timing, and response body
ElementsDoes the rendered DOM match expected state?Inspect the live page rather than guessing from source

In the Sources panel, add a breakpoint on the line that uses a suspicious value. Step over a line to run it, step into a function to inspect its implementation, or resume to the next pause. Conditional breakpoints are useful when a problem appears only for one record. Remove exploratory breakpoints after fixing the issue.

  1. Reproduce the issue with a short, repeatable sequence and note the expected result.
  2. Read the first meaningful console error and inspect its stack trace.
  3. Set a breakpoint before the first incorrect state; inspect values and the call stack.
  4. Change one cause, repeat the same steps, and verify nearby behaviour still works.
// Part 06 — Network and browser state

Trace the Boundary Between Your Code and the Web

When an API-driven page fails, look at the Network panel before rewriting the fetch call. A request may be blocked, sent to the wrong URL, rejected by the server, or answered with data your code did not expect. Status, headers, response body, and timing distinguish these cases. Avoid copying authorization headers or personal response data into public bug reports.

safe-json.js
javascript
async function readJson(response) {
  const contentType = response.headers.get('content-type') || ''
  if (!contentType.includes('application/json')) {
    throw new TypeError('Expected a JSON response')
  }

  const data = await response.json()
  if (data === null || typeof data !== 'object') {
    throw new TypeError('Response data has an unexpected shape')
  }
  return data
}

Validate only what your feature actually depends on. A check that confirms an object exists does not prove that every expected property is valid; validate required fields before using them. For local browser bugs, try a clean reload, preserve logs across navigation when needed, and compare the failing state with a known-good state.

📌 Real World Example
If an order history shows an empty list, the Network response can tell you whether the account truly has no orders or whether the server sent an error body that the UI mistakenly treated as a list.
// Part 07 — Pitfalls

Common Error-Handling Mistakes

Catching an error and returning an empty success value

Why: The caller cannot distinguish failure from a valid empty result.

Fix: Return an explicit error state, rethrow, or recover with a clearly documented fallback.

Using a synchronous catch around an un-awaited promise

Why: The rejection happens after the try block has finished.

Fix: Await the promise inside try or attach a rejection handler at the call site.

Showing stack traces to end users

Why: Developer diagnostics can expose internal details and confuse users.

Fix: Log diagnostic context safely; show a concise message and next action.

Retrying every request automatically

Why: Input, authorization, and validation failures are usually not transient.

Fix: Retry only failures known to be transient, with a bounded policy and user-visible status.

// Part 08 — Practice

Debug a Course Search Screen

Practice

Make failure states reproducible and recoverable

  1. Write a parseAmount function that rejects blank, non-finite, zero, and negative values with a useful error.
  2. Add a CourseNotFoundError and show a distinct not-found state without swallowing unexpected errors.
  3. Update a fetch-based loader to check response.ok and handle invalid JSON separately from network failure.
  4. Use a breakpoint to inspect a deliberately incorrect search result; write down which value first became wrong.
  5. Use DevTools Network to simulate or inspect a failed request, then verify the retry action clears the error state.

Hint: Keep validation at the input boundary, and keep developer diagnostics separate from the learner-facing message.

🎯 Key Takeaways

  • ✓Treat failures as normal cases; classify them before choosing how to recover.
  • ✓Throw Error objects with useful names and messages, and catch only where you can make a decision.
  • ✓Await asynchronous work inside try/catch; fetch requires an explicit response.ok check.
  • ✓Use breakpoints, the call stack, and Network details to find the first incorrect state.
  • ✓Show users a safe, useful message while preserving diagnostic information for development.
  • ✓Avoid silent fallbacks and unbounded retries that make failures look like success.

Next

What comes next

You can now reason about failures in the browser. Next, learn how promises and the event loop coordinate asynchronous work, then build reliable fetch flows with loading and error states.

Lesson 09 · Async JavaScript — Promises, async/await and fetch →

HELP US IMPROVE

How was this lesson?

Your note is shared with the Chaduvuko team for review. Please don’t include personal or sensitive information.

Choose your feedback

Spotted a mistake or something unclear? Suggest a fix on GitHub or email us. Select the text first and it is quoted for you.

Share

Discussion

0

Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.

Continue with GitHub
Loading...