¿Existe una forma sencilla de detectar un error en una API (servidor) que utiliza Node.js y Sequelize (Modelos)? Aquí está mi código (usa 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 = routerAsí es como manejo un error en el cliente:
axios.post(`http://localhost:9000/operations/add`, data) .then(res => console.log(`op added! (${res.status})`)) .catch(err => console.log(`wrong! (${err.response.status} )`))No quiero nada lujoso, ¡pero siéntete libre de probar lo que quieras!
Si desea manejar el error específico, adjunte un controlador .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) } });Si desea manejar los errores de manera más general (es decir, mostrar un buen mensaje de error, en lugar de matar su servidor, es posible que desee echar un vistazo a la excepción no controlada
https://nodejs.org/api/process.html#process_event_uncaughtexception
Si está utilizando Express, también contiene algunas funciones de manejo de errores http://expressjs.com/en/guide/error-handling.html