4

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.

Alfredo Bazo Lopez
  • 323
  • 1
  • 4
  • 12

3 Answers3

4

In app.js write this below where you've imported routes

const express = require('express');
const app = express();

app.use((req, res, next)=>{
  res.status(404).send({message:"Not Found"});
});

if you want to display some page from backend

app.use((req, res, next)=>{
  res.render('./path/to/file');
});

For more reference check this github project

nodejs_boiler_plate/app.js

Atishay Jain
  • 1,425
  • 12
  • 22
4

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.

Ridham Tarpara
  • 5,970
  • 4
  • 19
  • 39
1

Try Something Like:

app.get('*', (req, res) => {
  res.send({error: "No routes matched"});
  res.end();
})

Add this code as a last route in your routes and i hope so will do the magic.

Rahul kumar
  • 44
  • 1
  • 9