JavaScript · Intermediate level

Intermediate level · Module 5: Debugging and Code Quality in JavaScript · Lesson 3 of 3

Designing Error Handling

Create custom error types, decide where errors are caught and show users helpful messages while logging details for developers.

In this lesson you will

  • Create custom Error subclasses with useful information
  • Separate user-facing messages from developer details

Key concepts

Error subclasserror.causewhere to catchuser vs developer messages

The lesson

Custom errors make problems easy to distinguish: class NetworkError extends Error, class ValidationError extends Error. Use the cause option to keep the original error: new NetworkError("Could not load rates", { cause: err }).

Throw errors where problems are detected and catch them where you can respond — usually in the user-interface layer. Low-level functions should not show alerts or change the page.

Users need short, actionable messages: 'Could not load rates. Showing rates from yesterday.' Developers need details: log the full error with its cause to the console or a monitoring service.

Step by step

  1. Create NetworkError and ValidationError classes.
  2. Throw them from the API and form modules.
  3. Catch them in the UI and show friendly messages.
  4. Log full details with console.error.

Practice activity

Refactor the budget app's error handling into custom error types caught only in the UI layer.

Expected result: Every failure shows a friendly message, the console has full details and lower modules contain no UI code.

Check your understanding

  1. Why create custom error classes?

    Show answer

    So different problems can be recognised and handled differently.

  2. Where should most errors be caught in a web app?

    Show answer

    In the user-interface layer, where the app can respond to the user.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.