Bird
Raised Fist0
Expressframework~5 mins

Custom error classes in Express

Choose your learning style10 modes available
Introduction

Custom error classes help you create specific error types. This makes your code easier to understand and handle errors better.

When you want to handle different errors in different ways in your Express app.
When you want to add extra information to errors, like status codes.
When you want to keep your error handling clean and organized.
When you want to send clear error messages to users or logs.
Syntax
Express
class CustomError extends Error {
  constructor(message) {
    super(message);
    this.name = 'CustomError';
    this.statusCode = 400; // example status code
  }
}

Always extend the built-in Error class.

Set this.name to your custom error name for easier identification.

Examples
This error represents a 'Not Found' situation with status code 404.
Express
class NotFoundError extends Error {
  constructor(message) {
    super(message);
    this.name = 'NotFoundError';
    this.statusCode = 404;
  }
}
This error is for validation problems with status code 422.
Express
class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = 'ValidationError';
    this.statusCode = 422;
  }
}
Sample Program

This Express app uses a custom NotFoundError. When an item is missing, it sends a 404 error with a clear message.

Express
import express from 'express';

class NotFoundError extends Error {
  constructor(message) {
    super(message);
    this.name = 'NotFoundError';
    this.statusCode = 404;
  }
}

const app = express();

app.get('/item/:id', (req, res, next) => {
  const item = null; // pretend we searched but found nothing
  if (!item) {
    return next(new NotFoundError('Item not found'));
  }
  res.send(item);
});

app.use((err, req, res, next) => {
  if (err instanceof NotFoundError) {
    return res.status(err.statusCode).json({ error: err.message });
  }
  res.status(500).json({ error: 'Internal Server Error' });
});

export default app;
OutputSuccess
Important Notes

Use instanceof to check for your custom error type in middleware.

Always call super(message) in the constructor to set the error message.

Custom errors help keep your error handling clear and consistent.

Summary

Custom error classes extend the built-in Error to add specific error types.

They help you send proper status codes and messages in Express apps.

Use them to organize and improve your error handling.

Practice

(1/5)
1. What is the main purpose of creating a custom error class in an Express application?
easy
A. To define specific error types with custom messages and status codes
B. To replace the Express framework's built-in error handling completely
C. To avoid using try-catch blocks in asynchronous code
D. To automatically fix errors in the application code

Solution

  1. Step 1: Understand the role of custom error classes

    Custom error classes extend the built-in Error class to represent specific error types with meaningful messages and HTTP status codes.
  2. Step 2: Compare with other options

    Custom errors do not replace Express error handling but improve it; they do not fix code automatically or remove the need for try-catch.
  3. Final Answer:

    To define specific error types with custom messages and status codes -> Option A
  4. Quick Check:

    Custom error classes = specific error types [OK]
Hint: Custom errors add meaning and status codes to errors [OK]
Common Mistakes:
  • Thinking custom errors fix bugs automatically
  • Believing they replace Express error middleware
  • Assuming they remove try-catch necessity
2. Which of the following is the correct way to define a custom error class named NotFoundError that sets a 404 status code?
easy
A. function NotFoundError() { this.message = 'Not Found'; this.status = 404; }
B. class NotFoundError extends Error { constructor() { this.message = 'Not Found'; this.status = 404; } }
C. class NotFoundError { constructor() { this.message = 'Not Found'; this.status = 404; } }
D. class NotFoundError extends Error { constructor() { super('Not Found'); this.status = 404; } }

Solution

  1. Step 1: Check class inheritance and constructor

    The custom error class must extend Error and call super() with the message to set the error message properly.
  2. Step 2: Verify setting status property

    Setting this.status = 404 inside the constructor is correct for HTTP status code.
  3. Final Answer:

    class NotFoundError extends Error { constructor() { super('Not Found'); this.status = 404; } } -> Option D
  4. Quick Check:

    Extend Error + super() + status property = correct syntax [OK]
Hint: Always call super(message) when extending Error [OK]
Common Mistakes:
  • Not calling super() in constructor
  • Defining error as plain class without extending Error
  • Using function instead of class for custom error
3. Given the following code, what will be the output when 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);
}
medium
A. Invalid input 400
B. Invalid input undefined
C. ValidationError 400
D. Error Invalid input

Solution

  1. Step 1: Understand the error message and status

    The ValidationError constructor calls super(message), so err.message is 'Invalid input'. The status property is set to 400.
  2. Step 2: Check console.log output

    Logging err.message and err.status prints 'Invalid input' and 400 separated by space.
  3. Final Answer:

    Invalid input 400 -> Option A
  4. Quick Check:

    err.message = 'Invalid input', err.status = 400 [OK]
Hint: super(message) sets err.message; status is custom property [OK]
Common Mistakes:
  • Expecting class name as message
  • Assuming status is undefined
  • Confusing Error default message with custom message
4. Identify the error in this custom error class definition:
class AuthError extends Error {
  constructor(message) {
    this.message = message;
    this.status = 401;
  }
}
medium
A. Constructor should not accept message parameter
B. Status code 401 is invalid for authentication errors
C. Missing call to super(message) in constructor
D. Class should not extend Error for custom errors

Solution

  1. Step 1: Check constructor of subclass of Error

    When extending Error, the constructor must call super(message) to properly initialize the error message.
  2. Step 2: Identify missing super call

    The code sets this.message directly but does not call super(), which causes errors in Error inheritance.
  3. Final Answer:

    Missing call to super(message) in constructor -> Option C
  4. Quick Check:

    Always call super(message) in Error subclass constructor [OK]
Hint: Always call super() first in Error subclass constructor [OK]
Common Mistakes:
  • Setting this.message without super()
  • Forgetting to extend Error
  • Using wrong status codes for errors
5. You want to create a custom error class 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?
hard
A. class DatabaseError extends Error { constructor(message, code = 500) { super(message); this.status = code; this.code = 500; } }
B. class DatabaseError extends Error { constructor(message, code) { super(message); this.status = code || 500; this.code = code || 500; } }
C. class DatabaseError extends Error { constructor(message, code = 500) { super(message); this.status = 500; this.code = code; } }
D. class DatabaseError extends Error { constructor(message, code) { this.message = message; this.status = 500; this.code = code || 500; } }

Solution

  1. Step 1: Check constructor parameters and defaults

    class DatabaseError extends Error { constructor(message, code) { super(message); this.status = code || 500; this.code = code || 500; } } uses code parameter without default but uses code || 500 to set status and code, supporting optional code.
  2. Step 2: Verify super call and property assignments

    super(message) is called correctly; this.status and this.code are set to code or 500 if code is falsy.
  3. Step 3: Compare with other options

    class DatabaseError extends Error { constructor(message, code = 500) { super(message); this.status = 500; this.code = code; } } sets status always to 500 ignoring code parameter; class DatabaseError extends Error { constructor(message, code = 500) { super(message); this.status = code; this.code = 500; } } swaps status and code values; class DatabaseError extends Error { constructor(message, code) { this.message = message; this.status = 500; this.code = code || 500; } } misses super() call.
  4. Final Answer:

    class DatabaseError extends Error { constructor(message, code) { super(message); this.status = code || 500; this.code = code || 500; } } -> Option B
  5. Quick Check:

    Optional code with fallback and super() call = correct [OK]
Hint: Use code || 500 to set optional code with default [OK]
Common Mistakes:
  • Ignoring super() call
  • Swapping status and code values
  • Not supporting optional parameter correctly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard