JavaScript: Error

An Error object describes a failure with a name, message, and often a stack that helps developers diagnose it.

What you will learn

Minimal example

function requireId(value) {
  if (!value) {
    throw new Error('An id is required');
  }
  return value;
}

try {
  requireId('');
} catch (error) {
  console.error(error.name, error.message);
}

Throw an Error when a function cannot fulfill its contract. Catch it at a layer that can recover or report the failure meaningfully.

Common mistakes