Skip to content
Async JavaScriptChapter 36 / 47Intermediate5 min read

Error Handling

Learn JavaScript try catch error handling, finally, throw, custom error classes, Error cause, and how to handle async errors the right way.

On this page

1. What is error handling?

When JavaScript sees a mistake (like reading a property on undefined), it throws an error. If nobody catches it, it travels up out of the function and its callers and stops the program.

With try / catch you catch the error, with throw you send an error yourself, and with finally you do cleanup.

2. Why does it matter?

The network fails, users enter wrong input, the server sends a 500. If these are not handled, the user gets a blank screen and you do not even know what happened.

Without handlingWith proper handling
One error, the whole feature stopsThe error is caught, the rest of the app keeps running
The user sees a blank screenA clear message and a retry option
The cause of the bug is unknownThe error message, cause, and stack are logged
Every error looks the sameCustom classes give different responses

3. Where is it used?

PlaceExample
API callsShowing a message on a network or HTTP error
JSON parsingJSON.parse throws SyntaxError on bad text
Form validationThrowing ValidationError and highlighting the field
LibrariesTypeError or RangeError on a bad argument
LoggingSending errors to a monitoring service

4. How does it work?

The journey of an error
Code runs inside the try block
An error is thrown somewhere
The rest of try is skipped, control goes to catch
catch runs with the error object
finally always runs
Built-in errorWhen it happens
TypeErrorAn operation on the wrong type, like null.name
ReferenceErrorThe variable does not exist
SyntaxErrorBad syntax, or JSON.parse fails
RangeErrorA value is out of range
AggregateErrorMany errors at once, like from Promise.any

5. Code example

try, catch, finally

js
function parseSettings(text) {
  try {
    return JSON.parse(text);
  } catch (error) {
    console.warn("Settings are broken, using defaults:", error.message);
    return { theme: "light" };
  } finally {
    console.log("Parse attempt finished");
  }
}

parseSettings("{ bad json");

Custom error class and cause

js
class ApiError extends Error {
  constructor(message, { status, cause } = {}) {
    super(message, { cause });
    this.name = "ApiError";
    this.status = status;
  }
}

async function getProfile() {
  let res;
  try {
    res = await fetch("/api/profile");
  } catch (error) {
    throw new ApiError("Network failed", { cause: error });
  }
  if (!res.ok) throw new ApiError("Profile load failed", { status: res.status });
  return res.json();
}

try {
  await getProfile();
} catch (error) {
  if (error instanceof ApiError && error.status === 401) {
    console.log("Please log in again");
  } else {
    console.error(error, error.cause);
  }
}

How does the code work?

LineWhat is happening
JSON.parse(text)Throws SyntaxError on bad text
finallyAlways runs, on success or on error
class ApiError extends ErrorYour own error type, with an extra status
super(message, { cause })Saves the original error in cause
instanceof ApiErrorA different response depending on the kind of error

Interview tip

Throw only Error objects, not strings. throw "fail" has no stack trace, and error.message comes out as undefined.

6. Common mistakes

Mistake: An empty catch block

Why? The error is silently swallowed and finding the bug becomes impossible.

Better: At least log it, or rethrow an error that you cannot handle.

Mistake: Trying to catch an async error in an outer try

Why? An error from a setTimeout callback or a promise without await arrives later, by which time the try block has already finished.

Better: Use await, or put your own try catch inside the callback.

Mistake: Losing the original error when creating a new one

Why? Only the new message survives, and the original cause and stack are lost.

Better: Use new Error(message, { cause: originalError }).

Mistake: Adding try catch in every function

Why? The code gets heavy and errors are handled at the wrong level.

Better: Catch where you can respond to the user or retry.

7. What to learn before and after

Suggested order
Promises
Async Await
Fetch API
Error Handling
Debugging

Final quick revision

PointDetail
try / catchCatch an error
finallyCleanup that always runs
throwSend an error yourself, always an Error object
Custom errorclass X extends Error, set the name
causeAttach the original error to the new error
Asynctry / catch with await, or .catch()