Search code examples
typescriptfast-csv

With fast-csv how on data-invalid, how do I access the error object?


Using the fast-csv also supports async validation, with a callback example at

fast-csv examples

How do I get access to the error in the 'data-error' event?

The validate event has a callback with prototype of error, boolean, string.

.validate((row: Winner, processValidationError): void => {
  const valid = /^[a-zA-Z0-9\\]*$/.test(row.groupId);
  if (valid) {
    return processValidationError(null, false,'ok' )
  }
  // Error, boolean, reason: string
  const error = new WinnerValidationError("Failed to read groupId", 'groupId')
  return processValidationError(error, true,'groupId is invalid');
  })
}

On data-invalid the prototype is row, row number string and no error

 .on('data-invalid', (row, rowNumber: number, reason: string) => {
  console.log(error.message + error.key, `Invalid [rowNumber=${rowNumber}] 
    [row=${JSON.stringify(row)}] [reason=${reason}]`)
    processValidationError(row,rowNumber,reason)
  })

Solution

  • The error is passed in as the third argument (reason):

    .on('data-invalid', (row, rowNumber, reason) => {
        console.log(`Invalid row ${rowNumber}: ${reason}`);
    })
    

    If you throw an error instead of a string (which is good practice), you can access it as follows:

    .on('data-invalid', (row, rowNumber, error) => {
        console.log(`Invalid row ${rowNumber}: ${error.message}`);
    })