So the idea is that I have a controller that asks an object in a model to make a document in the database. I have a middleware that triggers after an error is thrown in the controller. But if an error is thrown in the model then it is not caught by the errorHandeler. Now my question is if that is posible to do. I can catch the error in the model and then the server doesn’t crash, however I don’t know how to give the info about that to the frontend.
Now for some code. I will try to only show the things that matter.
module.exports.post_groep = async (req, res, next) => {
try {
if (req.body.naam == "") {
throw Error("Invalid field: naam");
}
const groep_id = await Groep.postGroep(db_naam, req.body);
res.json({ groep: groep_id });
} catch (err) {
return next(err);
}
};
Above is the controller, the first step within the process that matters.
const handleErrors = (err) => {
let errors = { naam: "", afdeling: "" };
console.log(err);
if (err.code === 11000) {
errors.naam = "Naam reeds ingebruik";
return errors;
}
if (err.message === "Invalid field: naam") {
errors.naam = "Gelieve het veld naam in te geven";
}
return errors;
};
const errHandler = (err, req, res, next) => {
const errors = handleErrors(err);
return res.status(400).json({ errors });
};
module.exports = errHandler;
This is obviously the errorhandler. I know for a fact that the thrown error(“Invalid field: naam”) works. I only need to get the err.code === 11000 to work for now.
class Groep {
static async postGroep(db, obj, next) {
try {
/*if (obj.naam == "") {
throw new Error("Invalid field: naam");
}*/
const validate = ajv.compile(schema);
const valid = validate(obj);
if (valid) {
return await connector.queryPoster(db, "groepen", obj, true);
}
} catch (err) {
/*console.error(err.code);*/
return next(err);
/*if (err.code == 11000) {
throw Error("Duplicate field offence");
}*/
}
}
As you can see is the connection to the database handled in the model and that works fine. The part commented out within the try block is just me testing it out, however that works only then I would have the same problem as I now have with the duplicate error. the return next(err) within the catch block does not work. I’d need to comment that out and uncomment the line above to make it work without handling the error. The last part also works but it doesn’t get hanndled.