Skip to content
This repository was archived by the owner on Nov 3, 2020. It is now read-only.

Handle exceptions properly

sreen020 edited this page Jun 22, 2020 · 10 revisions

Handle exceptions properly
Everybody hates errors and most of all errors without an error message and nowhere to go. So we made an error page where you can find the information about the error (error code and error message). From here you know what’s going on and you can find a big call to action button saying “go back” to redirect to the home screen.

When im looking for http://localhost:3001/asdasd this is the page I get.

In my EJS file this is how I can show the error values:
<%= errorCode %> <%= message %>

This is the JS code:
router.get('/error', (req, res) => {
if (!req.session.user) {
return res.redirect('/');
}
return res.render('error');
});

router.use((req, res, next) => {
const error = new Error('Not found');
error.status = 404;
return res.render('error', {message: error.message, errorCode: error.status});
});

router.use((error, req, res, next) => {
res.status(error.status || 500);
res.json({
error: {
message: error.message,
},
});
});