Question: When an error occurs try catch stops an Express server from crashing. However, If the route doesn't stop how do I send the client an error page?
Background: Maybe I'm approaching this wrong but shouldn't the client receive an error page if there is a database error or similar problem?
Example: In the simplified example below try catch keeps the server from crashing. However, it also stops 500.html from being sent to the client because the event loop always reaches res.render('homepage') and sends that.
app.get('/', function(req, res, next) {
let cat = 10;
try {
if (cat === 10) throw new Error('cat should not be 10');
} catch(error) {
next(error);
}
res.render('homepage');
}
// custom error handler
app.use( function(error, req, res, next) {
console.log(error);
let filePath = path.join(__dirname, '/error-pages/500.html');
res.status(500).sendFile(filePath);
});
What I think you maybe are missing is that the next() function doesn't stop your application from going to the next instruction which is res.render('homepage');.
I believe that res.render('homepage'); runs before your handler has to oportunity to.
You could either place res.render('homepage'); inside the try block
app.get('/', function(req, res, next) {
let cat = 10;
try {
if (cat === 10) throw new Error('cat should not be 10');
res.render('homepage');
} catch(error) {
next(error);
}
}
or return inside the catch block. It will depend on what you wish from your logic.
app.get('/', function(req, res, next) {
let cat = 10;
try {
if (cat === 10) throw new Error('cat should not be 10');
} catch(error) {
return next(error);
}
res.render('homepage');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With