Create AppError with ValidationError (400), AuthError (401) and NotFoundError (404) subclasses, and a handle(fn) function that turns thrown errors into { status, body } responses – unknown errors become a 500 without leaking their message.
Solution
main.js
class AppError extends Error {
constructor(message, status) {
super(message);
this.name = this.constructor.name;
this.status = status;
}
}
class ValidationError extends AppError { constructor(m) { super(m, 400); } }
class AuthError extends AppError { constructor(m = "Please log in") { super(m, 401); } }
class NotFoundError extends AppError { constructor(what) { super(`${what} not found`, 404); } }
function handle(fn) {
try {
return { status: 200, body: fn() };
} catch (e) {
if (e instanceof AppError) return { status: e.status, body: `${e.name}: ${e.message}` };
return { status: 500, body: "Internal server error" }; // hide internal details
}
}
const routes = [
() => "Quiz list",
() => { throw new ValidationError("score must be 0–100"); },
() => { throw new AuthError(); },
() => { throw new NotFoundError("Quiz #42"); },
() => null.questions, // a real bug
];
for (const r of routes) {
const { status, body } = handle(r);
console.log(status, body);
}
Output Verified by running it on Node.js
200 Quiz list
400 ValidationError: score must be 0–100
401 AuthError: Please log in
404 NotFoundError: Quiz #42 not found
500 Internal server error
One base class carries the status; this.constructor.name names each subclass automatically. Errors the app did not expect fall through to a safe 500.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!