Performance: Custom error classes
This affects server response time and error handling efficiency, impacting how quickly errors are processed and sent to clients.
class NotFoundError extends Error { constructor(message) { super(message); this.name = 'NotFoundError'; this.status = 404; } } app.use((req, res, next) => { try { // some code } catch (err) { next(err); } });
app.use((req, res, next) => {
try {
// some code
} catch (err) {
err.status = 500;
next(err);
}
});| Pattern | Error Object Creation | Type Checking | Stack Trace Clarity | Verdict |
|---|---|---|---|---|
| Modifying generic Error objects dynamically | Low cost | High cost due to repeated checks | Unclear or inconsistent | [X] Bad |
| Using custom error classes with fixed properties | Low cost | Low cost with instanceof checks | Clear and consistent | [OK] Good |
NotFoundError that sets a 404 status code?throw new ValidationError('Invalid input'); is caught and logged?class ValidationError extends Error {
constructor(message) {
super(message);
this.status = 400;
}
}
try {
throw new ValidationError('Invalid input');
} catch (err) {
console.log(err.message, err.status);
}class AuthError extends Error {
constructor(message) {
this.message = message;
this.status = 401;
}
}DatabaseError that accepts a message and an optional error code, defaulting to 500. Which implementation correctly supports this and sets both status and code properties?Pass the test and this pattern moves unknown