How to create a custom error in JavaScript
Creating custom error classes allows you to handle different error types distinctly and add application-specific context to errors. As the creator of CoreUI with over 25 years of JavaScript development experience, I’ve built custom error hierarchies for complex enterprise applications. The most effective solution is to extend the built-in Error class to create custom error types with additional properties. This approach enables precise error handling and better debugging with domain-specific error information.
Extend the Error class to create custom error types.
class ValidationError extends Error {
constructor(message, field) {
super(message)
this.name = 'ValidationError'
this.field = field
}
}
function validateEmail(email) {
if (!email.includes('@')) {
throw new ValidationError('Invalid email format', 'email')
}
return true
}
try {
validateEmail('invalid-email')
} catch (error) {
if (error instanceof ValidationError) {
console.error(`Validation failed for ${error.field}: ${error.message}`)
} else {
console.error('Unexpected error:', error)
}
}
The custom ValidationError class extends Error and adds a field property for additional context. Setting this.name ensures the error name appears correctly in stack traces. The instanceof operator allows you to catch and handle specific error types differently. This pattern enables you to create a hierarchy of custom errors like NetworkError, DatabaseError, or AuthenticationError, each with relevant properties and handling logic.
Best Practice Note
This is the same custom error approach we use in CoreUI to provide detailed error information for debugging and monitoring. Always call super(message) first in the constructor and set meaningful error names. Custom errors make error tracking and debugging significantly easier in large applications.



