0
0
Expressframework~10 mins

Custom error classes in Express - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a custom error class named MyError.

Express
class MyError extends [1] {
  constructor(message) {
    super(message);
    this.name = 'MyError';
  }
}
Drag options to blanks, or click blank then click option'
AError
BFunction
CArray
DObject
Attempts:
3 left
💡 Hint
Common Mistakes
Extending from Object or Array instead of Error.
Forgetting to call super(message) in the constructor.
2fill in blank
medium

Complete the code to throw the custom error with a message.

Express
throw new MyError([1]);
Drag options to blanks, or click blank then click option'
Anull
B123
Ctrue
D'Something went wrong'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a number or boolean instead of a string.
Forgetting quotes around the message.
3fill in blank
hard

Fix the error in the custom error class to properly set the prototype chain.

Express
class CustomError extends Error {
  constructor(message) {
    super(message);
    this.name = 'CustomError';
    [1];
  }
}
Drag options to blanks, or click blank then click option'
AObject.setPrototypeOf(this, CustomError.prototype)
Bthis.prototype = CustomError
Cthis.__proto__ = Error.prototype
DCustomError.prototype = this
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning prototype incorrectly causing instanceof to fail.
Using deprecated or wrong prototype assignments.
4fill in blank
hard

Fill both blanks to create a middleware function that catches CustomError and sends a 400 status.

Express
function errorHandler(err, req, res, next) {
  if (err instanceof [1]) {
    res.status([2]).send({ error: err.message });
  } else {
    next(err);
  }
}
Drag options to blanks, or click blank then click option'
ACustomError
B400
C500
DError
Attempts:
3 left
💡 Hint
Common Mistakes
Using generic Error instead of CustomError in instanceof.
Sending wrong status code like 500 for client errors.
5fill in blank
hard

Fill all three blanks to define a custom error with a status code property and use it in middleware.

Express
class [1] extends Error {
  constructor(message) {
    super(message);
    this.status = [2];
    this.name = '[3]';
  }
}

function handler(err, req, res, next) {
  res.status(err.status || 500).send({ error: err.message });
}
Drag options to blanks, or click blank then click option'
AValidationError
B400
DCustomError
Attempts:
3 left
💡 Hint
Common Mistakes
Mismatch between class name and error name string.
Forgetting to set the status property.