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

134
Visualizações
What kind of errors does this try-catch block handle?
//mongoose connection function

const connectDB = (url) => {
    return mongoose.connect(url, {
        useNewUrlParser: true,
        useUnifiedTopology: true
    })
    .then(() => console.log('Connected to database'))
    .catch(err=>console.log(`DB CONNECTION ERR ${err}`))
}

const port = process.env.PORT || 5000
const mongoURI = process.env.MONGO_URI

//start

const start = async () => {
    try {
        await connectDB(mongoURI)
        app.listen(port, () => console.log(`Server running at ${port}`))
    } catch (error) {
        console.log(error);
    }
    
}

start()

This is my basic server setup. I tried messing with mongoose connection setup and app.listen() too but the catch block (in try-catch) didn't handle anything. Does the catch block only handle the errors we throw?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The try/catch doesn't handle anything because you prevent it from seeing errors with this code in connectDB:

.catch(err=>console.log(`DB CONNECTION ERR ${err}`))

That converts rejection into fulfillment with the value undefined (the return value of console.log).

Just as you should avoid catching exceptions too early, you should avoid handling rejections too early. That's easiest (IMHO) if you consistently use async functions where possible:

const connectDB = async (url) => {          // *** Make it an `async` function
    await mongoose.connect(url, {           // *** Await connection
        useNewUrlParser: true,
        useUnifiedTopology: true
    });
    console.log('Connected to database');   // *** Connection worked
};

const port = process.env.PORT || 5000;
const mongoURI = process.env.MONGO_URI;

//start

const start = async () => {
    try {
        await connectDB(mongoURI);          // ** Now you'll see errors here
        app.listen(port, () => console.log(`Server running at ${port}`));
    } catch (error) {
        console.log(error);
    }
};

start();
about 4 years ago · Juan Pablo Isaza Relatório

0

  • "promise"(async funcs if you want) - throws error in .catch(), if not specified, it acts as usual

  • "usual" - throws an error into try{}catch(){} block

const port = process.env.PORT || 5000;
const mongoURI = process.env.MONGO_URI;

//
//
//

mongoose.connect(mongoURI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    // useFindAndModify: false,
    // useCreateIndex: true,
}).catch((e)=>{
    console.log('db error', e.message);
});

//
//
//

(async()=>{
    // main code
})();

app.listen(port, ()=>console.log(`Server running at http://localhost:${port}/`));

I refactored the code a little, it was painful to see 🙂🙂🙂

  1. Specify local address in the "listen log", good practice, shortcut from the IDE console to browser
  2. Two keys for db, I used them, maybe you will need
  3. Self-executing function, more
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