Daniiel1221
Daniiel1221

Reputation: 1

UnhandledPromiseRejectionWarning - UnhandledPromiseRejectionWarning - DeprecationWarning

I am getting this error ->

(node:18420) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'name' of undefined

at C:\Users\ohrid\Desktop\backend2\routes\categories.js:27:24
at Layer.handle [as handle_request] (C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\index.js:281:22     
at Function.process_params (C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\index.js:317:13)
at C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\index.js:284:7       
at Function.process_params (C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\index.js:275:10)
at logger (C:\Users\ohrid\Desktop\backend2\node_modules\morgan\index.js:144:5)

(node:18420) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)

(node:18420) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

My routes/categories.js:

const { Category } = require('../models/category')
const express = require('express')
const router = express.Router()
 
router.get(`/`, async (req, res) => {
    const categoryList = await Category.find()
 
    if (!categoryList) {
        res.status(500).json({ success: false })
    }
    res.status(200).send(categoryList)
})
 
router.get('/:id', async (req, res) => {
    const category = await Category.findById(req.params.id)
 
    if (!category) {
        res.status(500).json({
            message: 'The category with the given ID was not found.',
        })
    }
    res.status(200).send(category)
})
 
router.post('/', async (req, res) => {
    let category = new Category({
        name: req.body.name,
        icon: req.body.icon,
        color: req.body.color,
    })
    category = await category.save()
 
    if (!category)
        return res.status(400).send('the category cannot be created!')
 
    res.send(category)
})
 
router.put('/:id', async (req, res) => {
    const category = await Category.findByIdAndUpdate(
        req.params.id,
        {
            name: req.body.name,
            icon: req.body.icon || category.icon,
            color: req.body.color,
        },
        { new: true }
    )
 
    if (!category)
        return res.status(400).send('the category cannot be created!')
 
    res.send(category)
})
 
router.delete('/:id', (req, res) => {
    Category.findByIdAndRemove(req.params.id)
        .then((category) => {
            if (category) {
                return res
                    .status(200)
                    .json({
                        success: true,
                        message: 'the category is deleted!',
                    })
            } else {
                return res
                    .status(404)
                    .json({ success: false, message: 'category not found!' })
            }
        })
        .catch((err) => {
            return res.status(500).json({ success: false, error: err })
        })
})
 
module.exports = router

My app.js

const express = require('express')
const app = express()
const morgan = require('morgan')
const mongoose = require('mongoose')
const cors = require('cors')
const dotenv = require('dotenv')
require('dotenv/config')
 
app.use(cors())
app.options('*', cors())
 
//middleware
app.use(morgan('tiny'))
 
//Routes
const categoriesRoutes = require('./routes/categories')
const productsRoutes = require('./routes/products')
const usersRoutes = require('./routes/users')
const ordersRoutes = require('./routes/orders')
 
const api = process.env.API_URL
 
app.use(`${api}/categories`, categoriesRoutes)
app.use(`${api}/products`, productsRoutes)
app.use(`${api}/users`, usersRoutes)
app.use(`${api}/orders`, ordersRoutes)
 
mongoose
    .connect(
        'mongodb+srv://dani:[email protected]/e-shop?retryWrites=true&w=majority',
        {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            dbName: 'e-shop',
        }
    )
    .then(() => {
        console.log('Database connection is ready')
    })
    .catch((err) => {
        console.log(err)
    })
 
app.listen(4000, () => {
    console.log('server is running on http://localhost:4000')
})

What should I change?

Upvotes: 0

Views: 372

Answers (1)

Idan Dagan
Idan Dagan

Reputation: 11635

You don't have any error handling layer in your application.

If you use Express v5 and above, route handlers and middleware that return a Promise will catch the errors and will call next(value) automatically.

Otherwise, from asynchronous functions, you must pass them to the next() function, where Express will catch and process them.

That way, you won't get the UnhandledPromiseRejectionWarning.

Upvotes: 0

Related Questions