Consider this Node.js code defining a custom error class and using it:
class MyError extends Error {
constructor(message) {
super(message);
this.name = 'MyError';
}
}
try {
throw new MyError('Oops!');
} catch (e) {
console.log(e.name + ': ' + e.message);
}What will be printed to the console?
class MyError extends Error { constructor(message) { super(message); this.name = 'MyError'; } } try { throw new MyError('Oops!'); } catch (e) { console.log(e.name + ': ' + e.message); }
Look at how the name property is set in the constructor.
The custom error class sets this.name = 'MyError', so the error's name is 'MyError'. The message is 'Oops!'. Thus, the output is 'MyError: Oops!'.
Examine this code snippet:
class BadError extends Error {
constructor(message) {
this.message = message;
this.name = 'BadError';
}
}
try {
throw new BadError('Fail');
} catch (e) {
console.log(e instanceof Error);
}What will be logged to the console?
class BadError extends Error { constructor(message) { this.message = message; this.name = 'BadError'; } } try { throw new BadError('Fail'); } catch (e) { console.log(e instanceof Error); }
What happens when you access this without calling super() first?
Accessing this before calling super() in a subclass constructor throws a ReferenceError. Since the constructor throws an error, the catch block receives that error, which is a ReferenceError, so logging e instanceof Error is not reached. The code will throw a ReferenceError at runtime.
Choose the code that correctly creates a custom error class preserving the stack trace in Node.js:
Look for the standard way to capture stack trace in Node.js custom errors.
Option B calls super(msg), sets the name, and uses Error.captureStackTrace(this, CustomError) to properly capture the stack trace excluding the constructor call.
Look at this code:
class MyError extends Error {
constructor(message) {
super(message);
}
}
const err = new MyError('Problem');
console.log(err.name);What will be printed and why?
class MyError extends Error { constructor(message) { super(message); } } const err = new MyError('Problem'); console.log(err.name);
Check if the name property is set in the constructor.
The name property defaults to 'Error' unless explicitly set. Since this.name is not assigned, it remains 'Error'.
Why should developers create custom error classes instead of using the built-in Error class directly?
Think about how custom errors help in debugging and managing errors.
Custom error classes allow adding meaningful names and extra properties, making it easier to identify and handle different error types in code.