Custom error classes help you create specific error types. This makes it easier to find and fix problems in your code.
Custom error classes in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
class MyError extends Error { constructor(message) { super(message); this.name = 'MyError'; } }
Always extend the built-in Error class to keep standard error behavior.
Set the name property to your custom error class name for clear error identification.
class ValidationError extends Error { constructor(message) { super(message); this.name = 'ValidationError'; } }
class DatabaseError extends Error { constructor(message, code) { super(message); this.name = 'DatabaseError'; this.code = code; // extra info } }
try { throw new ValidationError('Invalid input'); } catch (err) { if (err instanceof ValidationError) { console.log('Caught a validation error:', err.message); } }
This program defines a custom error class and uses it to check if input is a number. It doubles the number if valid, or throws a custom error if not. The error is caught and handled gracefully.
class CustomError extends Error { constructor(message) { super(message); this.name = 'CustomError'; } } function checkNumber(num) { if (typeof num !== 'number') { throw new CustomError('Not a number!'); } return num * 2; } try { console.log(checkNumber(5)); console.log(checkNumber('hello')); } catch (err) { if (err instanceof CustomError) { console.log(`Custom error caught: ${err.message}`); } else { console.log('Unknown error:', err); } }
Always call super(message) in the constructor to set the error message.
Use instanceof to check for your custom error type when catching errors.
Custom errors improve code clarity and debugging experience.
Custom error classes let you create specific error types for your app.
Extend the built-in Error class and set a custom name.
Use them to handle errors clearly and add extra info if needed.
Practice
Solution
Step 1: Understand the purpose of custom errors
Custom error classes help identify and handle specific error cases clearly in your code.Step 2: Compare with other options
Custom errors do not speed up code, avoid try-catch, or replace Error class but extend it.Final Answer:
To define specific error types for clearer error handling -> Option AQuick Check:
Custom error purpose = Specific error types [OK]
- Thinking custom errors improve performance
- Believing custom errors remove need for try-catch
- Assuming custom errors replace built-in Error
MyError in Node.js?Solution
Step 1: Check class inheritance
Custom errors must extend the built-in Error class to behave like errors.Step 2: Verify constructor and name setting
The constructor calls super(message) and sets this.name to the class name for clarity.Final Answer:
class MyError extends Error { constructor(message) { super(message); this.name = 'MyError'; } } -> Option DQuick Check:
Extend Error and set name = MyError [OK]
- Not extending Error class
- Forgetting to call super(message)
- Not setting the error name property
class NotFoundError extends Error {
constructor(message) {
super(message);
this.name = 'NotFoundError';
}
}
try {
throw new NotFoundError('Item not found');
} catch (e) {
console.log(e.name + ': ' + e.message);
}Solution
Step 1: Understand custom error name
The custom error sets this.name = 'NotFoundError', so e.name is 'NotFoundError'.Step 2: Check the output format
The console.log prints e.name + ': ' + e.message, which becomes 'NotFoundError: Item not found'.Final Answer:
NotFoundError: Item not found -> Option BQuick Check:
Custom error name shows in output [OK]
- Assuming default 'Error' name instead of custom
- Confusing error type with TypeError
- Missing the custom name property effect
class ValidationError extends Error {
constructor(msg) {
this.message = msg;
this.name = 'ValidationError';
}
}Solution
Step 1: Check constructor for super call
When extending Error, constructor must call super() before using this.Step 2: Identify missing super call
The code sets this.message and this.name without calling super(msg), causing a runtime error.Final Answer:
Missing call to super() in constructor -> Option AQuick Check:
Always call super() first in subclass constructor [OK]
- Forgetting super() call causes ReferenceError
- Setting this.message before super()
- Extending wrong base class
AuthError that includes a statusCode property for HTTP status codes. Which implementation correctly adds this property and preserves the error behavior?Solution
Step 1: Check proper Error extension and constructor
The class must extend Error and call super(message) to set the error message correctly.Step 2: Verify additional property and name
Setting this.statusCode after super() adds the extra info; setting this.name clarifies error type.Final Answer:
class AuthError extends Error { constructor(message, statusCode) { super(message); this.name = 'AuthError'; this.statusCode = statusCode; } } -> Option CQuick Check:
Extend Error, call super(message), add extra properties [OK]
- Not calling super(message) in constructor
- Not extending Error class
- Missing message parameter in super call
