Home > database >  Best way to catch an error in Models? (Node.js Sequelize)
Best way to catch an error in Models? (Node.js Sequelize)

Time:12-03

Is there a simple way to catch an error in an API (server) that's using Node.js and Sequelize (Models)? Here is my code (it uses async await):

const router = express.Router()
const { Operations } = require('../models')

router.post('/operations/add', async (req, res) => {
    const operations = req.body
    await operations.create(operations)
    res.json(operations)
    console.log('op added!')
})

router.put('/operations/update/:id', async (req, res) => {
    const operationId = req.params.id
    const operationUpdatedData = req.body
    const operationById = await Operation.findOne({ where: { id: operationId } })
    const operationUpdated = await operationById.update(operationUpdatedData)
    res.json(operationUpdated)
    console.log('op updated!')
})

router.delete('/operations/delete/:id', async (req, res) => {
    const operationId = req.params.id
    await Operations.destroy({ where: { id: operationId } })
    res.send('op deleted!')
    console.log('op deleted!')
})

module.exports = router

This is how I handle an error in the client:

axios.post(`http://localhost:9000/operations/add`, data)
            .then(res => console.log(`op added! (${res.status})`))
            .catch(err => console.log(`wrong! (${err.response.status} )`))

I don't want anything fancy, but feel free to try whatever you want!

CodePudding user response:

If you want to handle the specific error, attach a .catch handler

router.post("/operations/add", async (req, res) => {
  try {
    const operations = req.body;
    await operations.create(operations);
    res.json(operations);
    console.log("op added!");
  } catch (error) {
    // handle error here if you want to send on front simply send
    console.log(error)
    res.json(error.message)
  }
});

If you want to handle errors more generally (i.e. show a nice error message, instead of killing your server, you might want to have a look at the unhandled exception

https://nodejs.org/api/process.html#process_event_uncaughtexception

If you are using express, it also contains some error handling facilities http://expressjs.com/en/guide/error-handling.html

  • Related