Skip to content

Data transforms error handling #574

Description

@CarlosVilasAlvarez

Hi, I'm having some trouble handling errors caused on data transform functions.
json2csv: 5.0.7
Node v16.13.2

When you run this code

const { AsyncParser } = require('json2csv');
const { Readable } = require('stream');

const mockData = [
  {
    id: 1,
    name: 'John',
    surname: 'Doe',
  },
  {
    id: 2,
    name: 'Jane',
    surname: 'Doe',
  }
];

const mockDataStream = Readable.from(mockData);

const dataTransform = (data) => {
  if (data.name === 'Jane') throw new Error('Unhandled error');
  return data;
};

const asyncParser = new AsyncParser({ transforms: [dataTransform] }, { objectMode: true });

try {
  const parsingProcessor = asyncParser.fromInput(mockDataStream).toOutput(process.stdout);
  parsingProcessor.promise(false).catch(err => {
    console.log('Something happened');
  });
} catch (error) {
  console.log('Hello?');
}

You cannot handle the exception, it'll be an unhandledException one.

Screenshot 2022-09-20 at 15 40 36

Only approach that works is to put a try catch inside the data transform function like this.

const dataTransform = (data) => {
  try {
    if (data.name === 'Jane') throw new Error('Unhandled error');
    return data;
  } catch (error) {
    return undefined;
  }
};

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions