Javascript throw new error
In JavaScript, you can throw a custom error using the throw
statement. Here's an example:
throw new Error('Something went wrong!');
This will throw a Error
object with the message "Something went wrong!".
You can also create a custom error class by extending the Error
constructor:
class MyError extends Error {
constructor(message) {
super(message);
this.name = 'MyError';
}
}
throw new MyError('Something went wrong!');
This will throw a MyError
object with the message "Something went wrong!" and the name
property set to "MyError".
You can also use the Error
constructor with additional properties:
throw new Error('Something went wrong!', { cause: new ReferenceError('Variable is not defined') });
This will throw a Error
object with the message "Something went wrong!" and an additional cause
property set to a ReferenceError
object.
You can also use the throw
statement with a string:
throw 'Something went wrong!';
This will throw a TypeError
object with the message "Something went wrong!".
It's worth noting that when you throw an error, it will propagate up the call stack until it is caught by a try
/catch
block or until it reaches the top of the stack and is automatically caught by the JavaScript runtime.
Here's an example of how you can catch an error:
try {
throw new Error('Something went wrong!');
} catch (error) {
console.error('Error caught:', error);
}
This will catch the Error
object and log it to the console.