JavaScript Error Object

JavaScript Error constructor is used to create Error objects. To create a new Error object, use the “new Error()” constructor expression. The instance of an error object is thrown when runtime errors occur.

It is widely used for debugging, exception handling, and input validation.

Syntax

new Error([message[, fileName[, lineNumber]]])

Parameters

  1. message(optional): A human-readable description of the error.
  2. fileName(optional): The value for the file property on the created Error object. Defaults to the file’s name containing the Error() constructor code.
  3. lineNumber(optional): The value for the lineNumber property on the created an Error object. Defaults to the line number containing the Error() constructor invocation.

Example 1: How to Use Error Object

let error = new Error('Oops!! There is a mistake');

console.log(error);

Output

Error: Oops!! There is a mistake
at Object.<anonymous> (/Users/ankitlathiya/Desktop/code/app.js:1:13)
at Module._compile (node:internal/modules/cjs/loader:1255:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1309:10)
at Module.load (node:internal/modules/cjs/loader:1113:32)
at Module._load (node:internal/modules/cjs/loader:960:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12)
at node:internal/main/run_main_module:23:47

Example 2: Throwing an Error

You can throw an Error object using the throw keyword. This is useful in functions to indicate that an error condition has occurred.

function doSomething() {
throw new Error('Oops!! There is a mistake');
}

Example 3: Catching an Error

Errors can be caught using a try…catch statement.

try {
doSomething();
} catch (error) {
console.log(error.message);
}

Output

Oops!! There is a mistake

Error types

There are the following types of Errors in Javascript.

  1. EvalError: It creates an instance representing an error regarding the global function eval().
  2. InternalError: It creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g., “too much recursion.”
  3. RangeError: It creates an instance representing an error when a numeric variable or parameter is outside its valid range.
  4. ReferenceError: It creates an instance representing an error when de-referencing an invalid reference.
  5. SyntaxError: It creates an instance representing a syntax error while parsing code in eval().
  6. TypeError: It creates an instance representing an error that occurs when a variable or parameter is not of a valid type.
  7. URIError: It creates an instance representing an error that occurs when encodeURI() or decodeURI() are passed invalid parameters.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.