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

Serializing Custom Errors

Making custom errors JSON-serializable and handling error properties that don't serialize by default.

Serializing Custom Errors

You'll learn how to make your custom error objects JSON-serializable so they don't lose information when logged or transmitted.

Why Custom Errors Don't Serialize by Default

When you create a custom error class (extending Error), you'll notice something frustrating: calling JSON.stringify() on it produces just {} — an empty object! This happens because error properties like name, message, and stack are non-enumerable by default, so JSON.stringify() skips them.

This becomes a problem when you need to log errors to external services, send them over networks, or store them for debugging. Your carefully crafted custom properties vanish.

Making Errors JSON-Friendly

You have two main approaches:

1. Implement toJSON() method:

class ValidationError extends Error {
  constructor(message, field) {
    super(message);
    this.name = 'ValidationError';
    this.field = field;
  }

  toJSON() {
    return {
      name: this.name,
      message: this.message,
      field: this.field,
      stack: this.stack
    };
  }
}

const err = new ValidationError('Invalid email', 'email');
console.log(JSON.stringify(err));
// {"name":"ValidationError","message":"Invalid email","field":"email","stack":"..."}

2. Create a serialization helper:

function serializeError(err) {
  return {
    name: err.name,
    message: err.message,
    stack: err.stack,
    ...err // spread any custom properties
  };
}

Think of serialization like packing a suitcase: you need to explicitly decide which items (properties) to include, because the default packer (JSON.stringify) doesn't know errors contain valuable non-visible items.

Key Takeaway: Custom errors need explicit serialization via toJSON() or helper functions because their important properties (name, message, stack) are non-enumerable and won't survive JSON.stringify() by default.