Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
JavaScript Error message Property
The message property of JavaScript Error objects contains a human-readable description of the error. It's automatically set when an error occurs and can also be customized when creating custom errors.
Syntax
error.message
Example: Accessing Error Message
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JavaScript Error message Property</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.sample {
font-size: 18px;
font-weight: 500;
color: #d32f2f;
margin: 10px 0;
}
.btn {
padding: 10px 20px;
font-size: 16px;
background-color: #1976d2;
color: white;
border: none;
cursor: pointer;
border-radius: 4px;
}
</style>
</head>
<body>
<button class="btn">CLICK HERE</button>
<h3>Click the button to see the error message</h3>
<script>
let sampleEle = document.querySelector(".sample");
document.querySelector(".btn").addEventListener("click", () => {
try {
// Intentional typo: confrm instead of confirm
confrm('Are you sure');
} catch (e) {
sampleEle.innerHTML = "Error: " + e.message;
}
});
</script>
</body>
</html>
Creating Custom Error Messages
<!DOCTYPE html>
<html>
<head>
<title>Custom Error Messages</title>
</head>
<body>
<script>
function validateAge(age) {
if (age < 0) {
throw new Error("Age cannot be negative");
}
if (age > 150) {
throw new Error("Age seems unrealistic");
}
return "Valid age: " + age;
}
let output = document.getElementById("output");
try {
console.log(validateAge(-5));
} catch (error) {
output.innerHTML += "<p>Error: " + error.message + "</p>";
}
try {
console.log(validateAge(200));
} catch (error) {
output.innerHTML += "<p>Error: " + error.message + "</p>";
}
</script>
</body>
</html>
Common Error Types and Messages
| Error Type | Example Message | Cause |
|---|---|---|
| ReferenceError | "variable is not defined" | Using undefined variables |
| TypeError | "Cannot read property 'x' of null" | Accessing properties on null/undefined |
| SyntaxError | "Unexpected token" | Invalid JavaScript syntax |
| Custom Error | Your custom message | Thrown with new Error() |
Key Points
- The
messageproperty is read/write - you can modify it after creating an error - Different browsers may format error messages slightly differently
- Custom error messages should be descriptive and user-friendly
- The message property doesn't include the error type - use
error.namefor that
Conclusion
The message property provides essential error information for debugging and user feedback. Use it in try-catch blocks to handle errors gracefully and create meaningful custom error messages.
Advertisements
