Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

214
Visualizações
How to improve a validation functionality which uses try/catch

I built a validation function in the NodeJS app which filters out the bad data and allows the insert of the good data into the DB

Link to example of what I did Snippet

I would like to write this better with fewer try/catch if that is possible but not sure how

This is the code of the validation I'm trying to make it better

function validateTimeInStatusInput({ startAt, endAt, lastContact, firstContact, candidateId, status }, index) {

    try {
        if (endAt && endAt <= startAt) {
            throw new Error(
              `End ${endAt} cannot be before start ${startAt} (for ${candidateId} in ${status})`
            );
          }
    } catch (error) {
        console.log("\x1b[31mThis is bad data | removing data " + index + ", error:\x1b[0m\n ");
        console.warn(error);
        return false;
    }

    try {
        if ([firstContact, lastContact].some(date => date && (date < startAt || date > endAt))) {
            throw new Error(
              `First contact ${firstContact} and last contact ${lastContact} must be between start ${startAt} and end ${endAt} (for ${candidateId} in ${status})`
            );
        }
    } catch (error) {
      console.log("\x1b[31mThis is bad data | removing data " + index + ", error:\x1b[0m\n");
        console.warn(error);
        return false;
    }

    try {
  if (lastContact && firstContact && lastContact < firstContact) {
    throw new Error(
      `Last contact ${lastContact} cannot be before first contact ${firstContact} (for ${candidateId} in ${status})`
    );
  }
  } catch (error) {
    console.log("\x1b[31mThis is bad data | removing data " + index + ", error:\x1b[0m\n");
      console.warn(error);
      return false;
  }

  console.log("\n\t\x1b[32mThis is good data, it will be inserted\x1b[0m\n");

  return true;
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Make a logger function to reduce unnescesarry try/catch blocks.

const green = "\x1b[32m";
const red = "\x1b[31m";
const endColor = "\x1b[0m\n";
const logColor = (colorStr, msg) => colorStr + msg + endColor;

const createErrorLogger = (index) => (error) => {
  console.log(
    logColor(red, `This is bad data | removing data ${index}, error:`)
  );
  console.warn(error);
  return false;
};
function validateTimeInStatusInput(
  { startAt, endAt, lastContact, firstContact, candidateId, status },
  index
) {
  const logError = createErrorLogger(index);
  if (endAt && endAt <= startAt)
    return logError(
      `End ${endAt} cannot be before start ${startAt} (for ${candidateId} in ${status})`
    );
  if (
    [firstContact, lastContact].some(
      (date) => date && (date < startAt || date > endAt)
    )
  )
    return logError(
      `First contact ${firstContact} and last contact ${lastContact} must be between start ${startAt} and end ${endAt} (for ${candidateId} in ${status})`
    );
  if (lastContact && firstContact && lastContact < firstContact)
    return logError(
      `Last contact ${lastContact} cannot be before first contact ${firstContact} (for ${candidateId} in ${status})`
    );
  console.log(`
    ${logColor(green, "This is good data, it will be inserted")}
`);
  return true;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

function validateTimeInStatusInput({
  startAt,
  endAt,
  lastContact,
  firstContact,
  candidateId,
  status
}, index) {

  try {
    if (endAt && endAt <= startAt) {
      throw new Error(
        `End ${endAt} cannot be before start ${startAt} (for ${candidateId} in ${status})`
      );
    }

    if ([firstContact, lastContact].some(date => date && (date < startAt || date > endAt))) {
      throw new Error(
        `First contact ${firstContact} and last contact ${lastContact} must be between start ${startAt} and end ${endAt} (for ${candidateId} in ${status})`
      );
    }

    if (lastContact && firstContact && lastContact < firstContact) {
      throw new Error(
        `Last contact ${lastContact} cannot be before first contact ${firstContact} (for ${candidateId} in ${status})`
      );
    }
  } catch (error) {
    console.log("\x1b[31mThis is bad data | removing data " + index + ", error:\x1b[0m\n");
    console.warn(error);
    return false;
  }

  console.log("\n\t\x1b[32mThis is good data, it will be inserted\x1b[0m\n");

  return true;
}

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda