Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal when calling a wrong endpoint using app.get?

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.

like image 458
Alfredo Bazo Lopez Avatar asked Jan 27 '23 09:01

Alfredo Bazo Lopez


1 Answers

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.

like image 100
Ridham Tarpara Avatar answered Jan 31 '23 04:01

Ridham Tarpara