Home > Blockchain >  I am trying to make custom errors if a path is not found in my server
I am trying to make custom errors if a path is not found in my server

Time:04-20

my app.js code.

// To make it clear to the consumer that the application is an API, prefix the endpoint with /api
app.use("/api/v1", auth);
app.use("/api/v1/pages", authRoute, pages);
app.use("/api/v1/users",authRoute, users);
app.use("/api/v1/books",authRoute, books);
app.use("/api/v1/authors",authRoute, authors);
app.use("/api/v1/chapters", authRoute, chapters);

const start = async () => {
  try {
    await conn(process.env.MONGO_URI); // Access the connection string in .env
    app.listen(PORT, () => console.log(`Server is listening on port ${PORT}`));
  } catch (err) {
    console.log(err);
  }
};

//rate limit 
const limit = rateLimit({
  windowMs: 1 * 60 * 1000,
  max: 25,
});

app.use(limit);

start();

export default app;

so if a user types in /api/v1/bookkks I am wanting to return a message saying that does not exist.

I currently get this in postman if it's typed wrong.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Error</title>
</head>

<body>
    <pre>Cannot GET /api/v1/chapter</pre>
</body>

</html>

note this is an API and I don't have any web page set up.

CodePudding user response:

You can achieve this using a simple Middleware in Express.

See the addition below, (404 middleware must be the last route defined in the app)

// To make it clear to the consumer that the application is an API, prefix the endpoint with /api
app.use("/api/v1", auth);
app.use("/api/v1/pages", authRoute, pages);
app.use("/api/v1/users", authRoute, users);
app.use("/api/v1/books", authRoute, books);
app.use("/api/v1/authors", authRoute, authors);
app.use("/api/v1/chapters", authRoute, chapters);

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

const start = async () => {
  try {
    await conn(process.env.MONGO_URI); // Access the connection string in .env
    app.listen(PORT, () => console.log(`Server is listening on port ${PORT}`));
  } catch (err) {
    console.log(err);
  }
};

  • Related