LearnFrenzy
Sign in Take a free test

Error Handling · Error Handling Coding Problems · Question 1

Map custom errors to HTTP responses in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links