Blog
Here's how you can serialize/deserialize an error into a plain object.

Here's how you can serialize/deserialize an error into a plain object.

In this article, we will review how you can serialize/deserialize an error into a plain object. We will look at:

  1. serializeError usage in Flyde

  2. What is Flyde?

  3. serialize-error package

serializeError usage in Flyde

I found the following import in flyde/core/src/remote-debugger/utils.ts.

import { serializeError } from "serialize-error";

and this function is used as shown below:

export const toString = (v: any) => {
  const type = typeof v;

  switch (type) {
    case "object":
      if (v instanceof Error) {
        return JSON.stringify(serializeError(v));
      }
      try {
        return JSON.stringify(v).substr(0, STRING_LIMIT);
      } catch (e) {
        return `Object (cannot stringify)`;
      }
    default:
      return `${v}`.substr(0, STRING_LIMIT);
  }
};

What is Flyde?

Flyde is an open-source visual programming for backend logic that integrates with existing codebases. Flyde bridges the gap between technical and non-technical team members. Product managers, designers, and backend developers can collaborate on the same visual flows.

Learn more about Flyde.dev.

serialize-error package

Serialize/deserialize an error into a plain object

Useful if you for example need to JSON.stringify() or process.send() the error.

Installation

npm install serialize-error

Usage

import {serializeError, deserializeError} from 'serialize-error';

const error = new Error('🦄');

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

const serialized = serializeError(error);

console.log(serialized);
//=> {name: 'Error', message: '🦄', stack: 'Error: 🦄\n    at Object.<anonymous> …'}

const deserialized = deserializeError(serialized);

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

Learn more about serialize-error.

About me:

Hey, my name is Ramu Narasinga. I study codebase architecture in large open-source projects.

Email: ramu.narasinga@gmail.com

Want to learn from open-source? Solve challenges inspired by open-source projects.

References:

  1. https://github.com/flydelabs/flyde/blob/main/core/src/remote-debugger/utils.ts#L1

  2. https://www.npmjs.com/package/serialize-error