Skip to content

Latest commit

 

History

History
69 lines (47 loc) · 2.13 KB

File metadata and controls

69 lines (47 loc) · 2.13 KB

About

Errors are useful to report when something is wrong or unexpected in a program or a piece of code.

They are javascript objects.

The main property of this object is message:

const error = new Error('Oops, something went wrong');

console.log(error.message);
// => "Oops, something went wrong"

Using the throw syntax, you can throw an Error.

throw new Error('Oops');

When an Error is thrown, the current execution is stopped and resumes in the first catch block of the call stack.

try {
  throw new Error('Oops');
} catch (error) {
  console.log(error.message);
  // => "Oops"
}

As any object in Javascript the Error can be "extended" to create Custom errors. You can use the instanceof syntax to check if the error caught is an instance of a particular object.

class CustomError extends Error {}

try {
  // ... Code that may throw an error
} catch (error) {
  if (error instanceof CustomError) {
    console.log('The error thrown is an instance of the CustomError');
  }
}

Error Types

In addition to the Error object, other built-in error objects exist. You can learn more about it here

Custom Errors

You can also define your own Custom error Type by creating a class that extends one of the built-ins Error Types

class MyCustomError extends Error {}

Throwing non errors

While the syntax throw is usually used to throw an Error object, Javascript is flexible and will let you throw a string, a null or any primitive type.

Error stacktraces

While this is not standard in Javascript, most of the Javascript environments implement a stack property on the Error objects, allowing you to get the stack trace of the error that was thrown.