Build an error class hierarchy: a base AppError with ValidationError and NotFoundError subclasses.
AppError extends Error, takes (message, options), and passes options on so cause works. Each class's name must be its own class name, without every subclass setting it by hand.
new ValidationError(field, message) keeps field as error.field.
new NotFoundError(resource, id) makes its own message, "User 7 not found" for ("User", 7), and has a status of 404.
instanceof must work at every level: a NotFoundError is also an AppError and an Error.
class AppError extends Error {
// your code
}
class ValidationError extends AppError {
// your code
}
class NotFoundError extends AppError {
// your code
}
// const error = new NotFoundError("User", 7);
// error.message; // "User 7 not found"
// error.name; // "NotFoundError"
// error.status; // 404
// error instanceof AppError; // true
// const invalid = new ValidationError("email", "Email is required");
// invalid.field; // "email"
// String(invalid); // "ValidationError: Email is required"
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…