The Error() constructor is used to create error objects in JavaScript. These objects represent runtime errors and provide information about the error, such as its name and message. Error objects can be thrown and caught using try...catch statements to handle errors gracefully in your code.
// Create a new Error object
const myError = new Error('Something went wrong!')
console.log(myError.name) // "Error"
console.log(myError.message) // "Something went wrong!"
You can use the Error() constructor to create custom error messages in your functions and handle exceptions using try...catch blocks.
function checkUsername(userName) {
if (userName) {
console.log(userName)
} else {
console.log('I execute')
throw new Error('No username provided')
console.log('I do not execute')
}
}
checkUsername()