Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

420
Views
Best way to catch an error in Models? (Node.js + Sequelize)

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!