I have several endpoints defined. I am doing the automation of all of them and in addition defining some scenarios where I should get an error.
For instance, one of the endpoints is: '/v1/templates'.
Now, imagine that by error, the user types '/v1/templatess'.
I am using app.get to deal with the known endpoints like this:
app.get(
'/v1/contents/:template_component_content_id',
controllers.template_component_contents.getById.bind(controllers.template_component_contents)
);
Is there any way to say that in case that the endpoint called does not match with any of the app.get() options, throw an ERROR?
Thanks in advance.
You can handle 404 withing express handlers.
In your main express file(may be index.js or app.js) just put following after your routing middleware.
app.use("/v1", your_router);
// catch 404 and forward to error handler
app.use((request, response, next) => {
// Access response variable and handle it
// response.status(404).send("Your page is not found"))
// or
// res.render("home")
});
You can achieve this with additional route also with
app.get('*', (req, res) => {})
But it's not advisable as it's regex operation and express already providing the inbuilt handler to handle 404 routes.
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