We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Handling Errors

Errors are thrown (and should be thrown by you) when a non-happy path is encountered in your code. For example:

  • Data received from an API is not in the expected format
  • The connection to a database is lost
  • A user tries to log in with an incorrect password

Like Python, when an error is thrown, JavaScript yeets the program out of its current context and into the nearest try/catch block, or, if there isn't one, it crashes the program. For example:

const titan = {};
console.log(titan.neck.thickness);
console.log("done");

The code above prints:

TypeError: Cannot read properties of undefined (reading 'thickness')

It never gets to console.log("done") because the error crashes the program. The same error can happen inside a function:

function getNeckThickness(titan) {
  return titan.neck.thickness;
}

Put the potentially error-throwing code in a try block. If an error is thrown, execution immediately jumps to the catch block, skipping any code in try that hasn't run yet:

try {
  console.log(getNeckThickness({}));
  console.log("what's a titan?");
} catch (err) {
  console.log(err.message);
}
console.log("done");

Which prints:

Cannot read properties of undefined (reading 'thickness')
done

A try/catch block lets the program handle errors gracefully without crashing.

Putting code inside a try/catch block is often called "wrapping" the code in it.

Assignment

One of the calls to getMessageRecord is throwing a text id not found error.