Я пытаюсь использовать next () в экспрессе, чтобы передать ошибку настраиваемому промежуточному программному обеспечению по маршруту ниже:
app.post("/api/persons", (req, res) => {
const findPerson = Person.findOne({ name: req.body.name });
if (findPerson.length) {
res.status(404).json({ error: "Name already exists" });
} else if (req.body && req.body.name && req.body.number) {
const person = new Person({
name: req.body.name,
number: req.body.number,
});
person
.save()
.then((savedPerson) => {
console.info("saved successfully.");
res.json(savedPerson).end();
})
.catch((err) => next(err));
app.use(morgan("tiny"));
} else {
res.status(404).json({ error: "Name or number missing" });
}
});
Я определил функцию промежуточного программного обеспечения, как показано ниже:
const errorHandler = (error, request, response, next) => {
console.error(error.message);
if (error.name === "CastError") {
return response.status(400).send({ error: "malformatted id" });
}
next(error);
};
app.use(errorHandler);
Я добавляю это промежуточное ПО в самый последний файл, после всех остальных app.use (). Но я продолжаю получать справочную ошибку, как показано ниже:
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().
Несмотря на то, что я явно использую блок catch, кажется, что это вызывает ошибку. Я попытался добавить определение обработчика ошибок вверху, но он по-прежнему показывает ту же ошибку.
Изменять
app.post("/api/persons", (req, res) => { // next is missing here
// ..///
});
К
app.post("/api/persons", (req, res, next) => { // add next here
// ../// next(err); // call next with error now
});
Since promises automatically catch both synchronous errors and rejected promises, you can simply provide next as the final catch handler and Express will catch errors, because the catch handler is given the error as the first argument.
Читать - https://expressjs.com/en/guide/error-handling.html
For errors returned from asynchronous functions invoked by route handlers and middleware, you must pass them to the next() function, where Express will catch and process them.
function errorHandler (err, req, res, next) {
if (res.headersSent) {
return next(err)
}
res.status(500)
res.render('error', { error: err })
}
@AbhishekGhadge Рад, что помог, Ура :)
Большое спасибо! Я совсем забыл добавить это в params.