¿Como enviar un código de estado http dependiendo de si hay un error o no?, mas específicamente el error que quiero controlar es si el objeto que envían al servidor cumple con ciertas validaciones
Lo que intenté:
Rutas:
const express = require('express')
const router = express.Router()
const dataBase = require('../database')
const employee = require('../models/Employee')
router.post('/addEmployee', async (req,res,next)=>{
try{
const obj = await req.body
const addEmployee = await employee.addEmployee(obj,dataBase.db)
res.sendStatus(200)
next()
}catch(e){
res.sendStatus(500)
}
})
module.exports = router
Employee Antiguo:
const MongoDB = require("mongodb");
const addEmployee = function (myobj, db) {
try {
const collection = db.collection("employees");
collection.insertOne(myobj, (err, res) => {
if(err){
console.log("Ocurrio un error al insertar el usuario".red,err.errmsg)
return
}
const id = res.ops[0]._id;
var date = new Date();
const dateFormat = `Fecha: ${date.getUTCDate()}/${date.getUTCMonth()}/${date.getUTCFullYear()} Hora: ${date.getUTCHours()}:${date.getUTCMinutes()}:${date.getUTCSeconds()} UTC`;
collection.findOneAndUpdate(
{ _id: id },
{ $set: { created_At: dateFormat } }
);
});
} catch (error) {
console.log("OCURRIO UN ERRO AL INSERTAR EL USUARIO".red, error);
throw error
}
};
const employee = {};
employee.addEmployee = addEmployee;
module.exports = employee;
Employee Nuevo:
const MongoDB = require("mongodb");
class UserError extends Error {
constructor(message) {
super();
this.message = message;
this.errorCode = 500;
}
}
const addEmployee = function (myobj, db) {
try {
const collection = db.collection("employees");
collection.insertOne(myobj, (err, res) => {
if(err){
throw new UserError('Ocurrio un error al insertar el usuario');
}
const id = res.ops[0]._id;
var date = new Date();
const dateFormat = `Fecha: ${date.getUTCDate()}/${date.getUTCMonth()}/${date.getUTCFullYear()} Hora: ${date.getUTCHours()}:${date.getUTCMinutes()}:${date.getUTCSeconds()} UTC`;
collection.findOneAndUpdate(
{ _id: id },
{ $set: { created_At: dateFormat } }
);
});
} catch (e) {
if(e instanceof UserError){
throw(e);
}else{
console.log(e)
}
}
};
const employee = {};
employee.addEmployee = addEmployee;
module.exports = employee;
Error que lanza (en consola, y sigue devolviendo status 200) esta ultima versión de employee al hacer una petición que no cumple las validaciones
throw err;
^
UserError: Ocurrio un error al insertar el usuario
at C:\Users\Franco\Desktop\APPS BACKEND AND FRONTEND\ADMINISTRADOR DE EMPLEADOS\backend\src\models\Employee.js:16:17
at executeCallback (C:\Users\Franco\Desktop\APPS BACKEND AND FRONTEND\ADMINISTRADOR DE EMPLEADOS\backend\node_modules\mongodb\lib\operations\execute_operation.js:70:5)
at C:\Users\Franco\Desktop\APPS BACKEND AND FRONTEND\ADMINISTRADOR DE EMPLEADOS\backend\node_modules\mongodb\lib\operations\insert_one.js:28:35
at handleCallback (C:\Users\Franco\Desktop\APPS BACKEND AND FRONTEND\ADMINISTRADOR DE EMPLEADOS\backend\node_modules\mongodb\lib\utils.js:128:55)
at C:\Users\Franco\Desktop\APPS BACKEND AND FRONTEND\ADMINISTRADOR DE EMPLEADOS\backend\node_modules\mongodb\lib\operations\common_functions.js:265:14
at handler (C:\Users\Franco\Desktop\APPS BACKEND AND FRONTEND\ADMINISTRADOR DE EMPLEADOS\backend\node_modules\mongodb\lib\core\sdam\topology.js:913:24)
at C:\Users\Franco\Desktop\APPS BACKEND AND FRONTEND\ADMINISTRADOR DE EMPLEADOS\backend\node_modules\mongodb\lib\cmap\connection_pool.js:352:13
at handleOperationResult (C:\Users\Franco\Desktop\APPS BACKEND AND FRONTEND\ADMINISTRADOR DE EMPLEADOS\backend\node_modules\mongodb\lib\core\sdam\server.js:489:5)
at MessageStream.messageHandler (C:\Users\Franco\Desktop\APPS BACKEND AND FRONTEND\ADMINISTRADOR DE EMPLEADOS\backend\node_modules\mongodb\lib\cmap\connection.js:270:5)
at MessageStream.emit (events.js:311:20) {
message: 'Ocurrio un error al insertar el usuario',
errorCode: 500
}
[nodemon] app crashed - waiting for file changes before starting...