是否有一種簡單的方法可以在使用 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} )`))
我不想要任何花哨的東西,但可以隨意嘗試任何你想要的!
uj5u.com熱心網友回復:
如果要處理特定錯誤,請附加.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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/371271.html
