On peux créer une view 500.ejs pour les problèmes de serveur :
// 500.ejs
<%- include('includes/head.ejs') %>
</head>
<body>
<%- include('includes/navigation.ejs') %>
<h1>Something went wrong! =( </h1>
<p>We are working on fixing this. Sorry for the inconvenient </p>
<p>Please try again later and contact-us if the problem persists</p>
<%- include('includes/end.ejs') %>
//App.js
app.get("/500", errorController.get500)
// controller/admin.js
.catch(err => {
res.redirect("/500")
});
Using the Express.js Error Handling Middleware :
Everytime express sees that you called next() with an error as an argument it will automatically go to the error handling middleware. If you have more than one it will be executed from top to bottom.
// controller/admin.js
.catch(err => {
// res.redirect("/500")
const error = new Error(err);
error.httpStatusCode = 500;
return next(error)
});
//app.js
// Errors handling middleware :
app.use((error, req, res, next) => {
res.redirect('/500')
})
Attention : Inside an async code snippet ( then / catch ... ) si on utilise throw new Error on n'atteint jamais le middleware error handling ! Si on veux l'atteindre depuis du code asynchrone il faut utiliser next() avec l'err en argument (next(new Error(err))) . Par ailleurs on peut utiliser throw new Error dans un code synchrone !
1×× Informational
2×× Success