The throw statement allows you to create a custom error. The throw statement throws (generates) an error. The throw statement throws an exception. The exception can be a JavaScript String, a Number, a Boolean or an Object.
throw "Too big"; // throw a text
throw 500; // throw a number
throw false; // throw a boolean
throw person; // throw an object
While the built-in Error class is fairly well defined—including such things as the filename, line number, and stack trace to name a few—when it comes down to it, the most important thing to take note of is the message. The first—and often only—parameter to be passed during Error instantiation, the message is a human-readable error that can often be related directly to the end user. Throwing a generic exception is almost as simple as it sounds. All it takes is to instantiate an exception object—with the first parameter of the Error constructor being the error message—and then… "throw" it.
throw new Error('Exception message');
It is important to note here that, while the error message is the human readable error data, Node.js also provides an error code that identifies the kind of error that is being thrown. This value is useful as it allows you to programmatically adapt to errors that may be thrown, regardless of the message contained within the error.
While error codes are generally used for system errors, when creating custom errors by extending the error class (see Custom exceptions below for more details), a custom code can be defined and used for more structured error definitions.
function CustomException(message) {
const error = new Error(message);
error.code = "THIS_IS_A_CUSTOM_ERROR_CODE";
return error;
}
CustomException.prototype = Object.create(Error.prototype);
While it is possible to throw any object, best practice is to extend the Error object with a new class. In environments that support it, this allows for features like the automatic stack trace to be included in the exception response, which can be crucial when it comes to diagnosing issues later down the line.
// Simple Custom Exception
function CustomException(message) {
this.message = message;
this.name = "CustomException";
}
// Function that throws the custom exception
function doSomething() {
try {
let value = false; // Simulate a failure
if (!value) {
throw new CustomException("This is a custom error message!");
}
console.log("Everything is fine!");
} catch (error) {
if (error instanceof CustomException) {
console.error(`Caught a Custom Exception: ${error.name} - ${error.message}`);
} else {
console.error(`An unexpected error occurred: ${error.message}`);
}
}
}
// Call the function
doSomething();
The try statement allows you to define a block of code to be tested for errors while it is being executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
The JavaScript statements try and catch come in pairs.
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
The finally statement lets you execute code, after try and catch, regardless of the result.
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
Block of code to be executed regardless of the try / catch result
}
JavaScript has a built in error object that provides error information when an error occurs. The error object provides two useful properties: name and message.
Property | Description |
---|---|
name | Sets or returns an error name |
message | Sets or returns an error message (a string) |
Six different values can be returned by the error name property.
Error Name | Description |
---|---|
EvalError | An error has occurred in the eval() function |
RangeError | A number "out of range" has occurred |
ReferenceError | An illegal reference has occurred |
SyntaxError | A syntax error has occurred |
TypeError | A type error has occurred |
URIError | An error in encodeURI() has occurred |
Eval Error