Course contentsShow
← JavaScript
Lesson 1154 of 2,72326. Error HandlingFree lesson

Adding Custom Properties to Errors

Attaching additional context like status codes, validation details, or metadata to error instances.

Adding Custom Properties to Errors

You'll learn how to attach extra context like status codes or validation details to your custom error objects.

Why Add Custom Properties?

When you throw an error, sometimes the message and stack trace aren't enough. You might need to include:

  • HTTP status codes (404, 500, etc.)
  • Validation failure details (which fields failed?)
  • Error codes for your API
  • User-facing vs internal messages
  • Timestamps or request IDs

Think of it like labeling a package: the address (error message) tells you where it's going, but extra labels (customs forms, tracking numbers) provide crucial context.

How to Add Custom Properties

When extending the Error class, you can assign any additional properties in your constructor:

class ValidationError extends Error {
  constructor(message, fieldErrors) {
    super(message);
    this.name = 'ValidationError';
    this.fieldErrors = fieldErrors;  // Custom property
    this.timestamp = Date.now();     // Custom property
  }
}

const error = new ValidationError(
  'Form validation failed',
  { email: 'Invalid format', age: 'Must be 18+' }
);

console.log(error.message);        // 'Form validation failed'
console.log(error.fieldErrors);    // { email: '...', age: '...' }
console.log(error.timestamp);      // 1704067200000

Practical Example

class ApiError extends Error {
  constructor(message, statusCode, errorCode) {
    super(message);
    this.name = 'ApiError';
    this.statusCode = statusCode;
    this.errorCode = errorCode;
  }
}

try {
  throw new ApiError('Resource not found', 404, 'NOT_FOUND');
} catch (error) {
  console.log(error.statusCode);  // 404
  console.log(error.errorCode);   // 'NOT_FOUND'
  // Now you can respond with the right HTTP status!
}

Key Takeaway: Custom properties turn errors from simple messages into rich data objects that carry all the context your error handlers need to respond appropriately.