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 the console.log("done") because the error crashes the program. But what if we use a try/catch block? We place the potentially error-throwing code in the try block, and if an error is thrown, execution immediately jumps to the catch block (ignoring any code in the try block that hasn't run yet):

try {
  const titan = {};
  console.log(titan.neck.thickness);
  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

Assignment

One of the calls to getMessageRecord is throwing a text id not found error. Change the code to safely make the function calls within a try-catch block. If an error is raised, print the error message to the console as a string.