diff --git a/server/middleware/errorHandler.js b/server/middleware/errorHandler.js new file mode 100644 index 0000000..ca69270 --- /dev/null +++ b/server/middleware/errorHandler.js @@ -0,0 +1,33 @@ +import { ValidationError, DatabaseError, UniqueConstraintError, ForeignKeyConstraintError } from 'sequelize'; + +export const sequelizeErrorHandler = (error, req, res, next) => { + if (error instanceof ValidationError) { + return res.status(400).json({ + error: error.errors.map(e => e.message) + }); + } + + if (error instanceof UniqueConstraintError) { + return res.status(409).json({ + error: 'Resource already exists' + }); + } + + if (error instanceof ForeignKeyConstraintError) { + return res.status(400).json({ + error: 'Invalid reference to related resource' + }); + } + + if (error instanceof DatabaseError) { + console.error('Database error:', error); + return res.status(500).json({ + error: 'A database error occurred' + }); + } + + console.error('Unexpected error:', error); + res.status(500).json({ + error: 'An unexpected error occurred' + }); +}; \ No newline at end of file diff --git a/server/models/todo.js b/server/models/todo.js index 9a86c0c..daf1977 100644 --- a/server/models/todo.js +++ b/server/models/todo.js @@ -12,11 +12,28 @@ Todo.init({ }, name: { type: DataTypes.STRING, - allowNull: false + allowNull: false, + validate: { + notNull: { + msg: 'name is required' + }, + notEmpty: { + msg: 'name cannot be empty' + } + } }, priority: { type: DataTypes.ENUM('low', 'medium', 'high'), - allowNull: false + allowNull: false, + validate: { + notNull: { + msg: 'priority is required' + }, + isIn: { + args: [['low', 'medium', 'high']], + msg: 'priority must be low, medium, or high' + } + } }, due_date: { type: DataTypes.DATE, diff --git a/server/routes/todos.router.js b/server/routes/todos.router.js index 609f6af..917edb8 100644 --- a/server/routes/todos.router.js +++ b/server/routes/todos.router.js @@ -2,6 +2,7 @@ import express from 'express'; import Todo from '../models/todo.js'; import validateTodo from '../middleware/todoValidation.js'; import { rejectUnauthenticated } from '../middleware/auth.js'; +import { sequelizeErrorHandler } from '../middleware/errorHandler.js'; const router = express.Router(); @@ -122,4 +123,8 @@ router.delete('/:id', async (req, res) => { } }); +// Add at the end of your router +router.use(sequelizeErrorHandler); + + export default router; \ No newline at end of file