【问题标题】:Best way to catch an error in Models? (Node.js + Sequelize)捕捉模型错误的最佳方法? (Node.js + 续集)
【发布时间】: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


    【解决方案1】:

    如果要处理特定错误,请附加.catch 处理程序

    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)
      }
    });
    

    如果您想更一般地处理错误(即显示一个很好的错误消息,而不是杀死您的服务器,您可能希望查看未处理的异常

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

    如果你使用express,它还包含一些错误处理工具http://expressjs.com/en/guide/error-handling.html

    【讨论】:

    • 太简单了,非常感谢,我怎样才能选择你作为最佳答案(我是新来的)?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多