• Serialize an Error object into a plain object.

    • Non-error values are passed through.
    • Custom properties are preserved.
    • Buffer properties are replaced with [object Buffer].
    • Circular references are handled.
    • If the input object has a .toJSON() method, then it's called instead of serializing the object's properties.
    • It's up to .toJSON() implementation to handle circular references and enumerability of the properties.

    Type Parameters

    • ErrorType

    Parameters

    Returns ErrorType extends Primitive
        ? ErrorType<ErrorType>
        : unknown extends ErrorType ? unknown : ErrorObject

    import {serializeError} from 'serialize-error';

    const error = new Error('🦄');

    console.log(error);
    //=> [Error: 🦄]

    console.log(serializeError(error));
    //=> {name: 'Error', message: '🦄', stack: 'Error: 🦄\n at Object.<anonymous> …'}
    import {serializeError} from 'serialize-error';

    class ErrorWithDate extends Error {
    constructor() {
    super();
    this.date = new Date();
    }
    }

    const error = new ErrorWithDate();

    console.log(serializeError(error));
    //=> {date: '1970-01-01T00:00:00.000Z', name, message, stack}
    import {serializeError} from 'serialize-error';

    const error = new Error('Unicorn');

    error.horn = {
    toJSON() {
    return 'x';
    }
    };

    serializeError(error);
    // => {horn: 'x', name, message, stack}