Try Catch Doesn't Return Error When There Is An Error

41 Views Asked by At

So I Put a try catch system that is checking if I can connect to my MongoDB an if it doesn't don't run the server.

When it does connect all well and good, when I try and check the error system (just console.log('error')). I changed my password and it doesn't return 'error' and just runs the server.

General code mockup:

const express = require('express')
const app = express()
const tasks = require('./routes/tasks')
const connectDB = require('./db/connect')


// middleware
app.use(express.json())

// routes
app.get('/hello', (req, res) => {
  res.send('<h2>i know how to do things</h2>')
})

app.post('/api/v1/tasks', tasks)
app.use('/api/v1/tasks', tasks)

const port = 3000;
const start = async () => {

try {
    await connectDB
    app.listen(port, console.log(`server is listening on port ${port}`))
} catch (error) {
    console.log('error')
}

}

start()

this is the code for the connectDB pull

const mongoose = require('mongoose')

const connectionString = "mongodb+srv://user:[email protected]/TASK-MANAGER?retryWrites=true&w=majority&appName=Cluster0"

const connectDB = (url) => {
    return mongoose.connect(connectionString, {
        useNewUrlParser: true,
        useCreateIndex: true,
        useFindAndModify: false,
        useUnifiedTopology: true,
    })
}

module.exports = connectDB

I've rewritten the code 3 times and I cannot get it working, I'm following "Node.js/Express Course - Build 4 Projects" on YouTube

1

There are 1 best solutions below

0
jQueeny On

Connecting to mongodb with mongoose is a very simple process. As a beginner you want to focus on getting things up and running, making queries and progress with your learning. Stick to the basics before abstracting things away into reusable modules.

  1. Delete all of this:
const start = async () => {
   try {
      await connectDB
      app.listen(port, console.log(`server is listening on port ${port}`))
   } catch (error) {
      console.log('error')
   }
}
start()
  1. Delete the entire connectDB module.
  2. Update your app.js file to use the mongoose.connect function like so:
const mongoose = require('mongoose');
const express = require('express');
const app = express();
const tasks = require('./routes/tasks');
const connectionString = "mongodb+srv://user:[email protected]/TASK-MANAGER?retryWrites=true&w=majority&appName=Cluster0";

// middleware
app.use(express.json());

// routes
app.get('/hello', (req, res) => {
  res.send('<h2>i know how to do things</h2>')
});

app.post('/api/v1/tasks', tasks);
app.use('/api/v1/tasks', tasks);

const port = 3000;
mongoose.connect(connectionString).then(()=>{
   console.log('Connected to mongodb');
}).catch(err =>{
   console.log('Error Connecting', err);
});

app.listen(port, () => {
    console.log(`Server listening on port ${port}`);
});
  1. Try to find a more up-to-date tutorial.