【发布时间】:2021-12-01 18:20:52
【问题描述】:
是否有一种简单的方法来捕获使用 Node.js 和 Sequelize(模型)的 API(服务器)中的错误?这是我的代码(它使用 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
这是我在客户端处理错误的方式:
axios.post(`http://localhost:9000/operations/add`, data)
.then(res => console.log(`op added! (${res.status})`))
.catch(err => console.log(`wrong! (${err.response.status} )`))
我不想要任何花哨的东西,但请随意尝试任何你想要的东西!
【问题讨论】:
标签: javascript node.js express sequelize.js