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

118
Visualizações
Make error inside `try` not handled by `catch`

I want the specific errors that are thrown inside try block not to be handled by catch(err)

Example:

const someFunc = async () => {
  ...
  try {
    ...
    // This error should not be handled by the catch and go straight to the middleware
    throw {
      status: 404,
      message: "Not Found",
    };
  } catch (error) {
    throw {
      status: 500,
      message: "Something went wrong",
      reason: error,
    };
  }
};

After that the middleware handles the errors.

export const errorHandler: ErrorRequestHandler = (err, req, res, next) => {
  const { status = 500, message, reason } = err;
  res.status(status).json({
    success: false,
    message: message || "Something went wrong",
    reason: reason || undefined,
  });
};
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

If you throw an error inside a try-block, the catch will catch it. The best you can do is to check in the catch-block if the error you don't want to catch is thrown and if so, rethrow it.

const someFunc = async () => {
  try {
    throw {
      status: 404,
      message: "Not Found",
    };
  } catch (error) {
    // If a 404 error is caught, rethrow it.
    if (error.status === 404) {
      throw error;
    }

    throw {
      status: 500,
      message: "Something went wrong",
      reason: error,
    };
  }
};
about 4 years ago · Santiago Trujillo 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