'express.js restfulApi, How to add an error message if the request to data.js is not found?

This is the code for the app.js file, it is for use as restful Api, I want to add a error message if the data in the array(data.js) is not found.

const express = require('express');
const data = require('./data');

// Initialize App
const app = express();

// Assign route
app.use('/api', (req, res, next) => {
    const filters = req.query;
    const filteredUsers = data.filter(user => {
      let isValid = true;
      for (key in filters) {
        console.log(key, user[key], filters[key]);
        isValid = isValid && user[key] == filters[key];
        
      }
    
      return isValid;
    });
   
    res.send(filteredUsers);
  });

// Start server on PORT 5000
app.listen(8080, () => {
console.log('Server started!');
});



Solution 1:[1]

you can send back a json as a response with 404 status and address the error, it would look something like this

if(!filteredUsers)
  res.status(404).send({
     error: "Data not found"
  })

or it can be a simple text

if(!filteredUsers.length)
   res.status(404).send("Data Not found")

Solution 2:[2]

You can return error in restful api noed js like this:

if (!data) return res.status(404).send({ msg: 'data not found' })

actually in your code you should use it like this:

const data = require('./data');


app.use('/api', (req, res, next) => {
if (!data) return res.status(404).send({ msg: 'data not found' })

    const filters = req.query;
    const filteredUsers = data.filter(user => {
      let isValid = true;
      for (key in filters) {
        console.log(key, user[key], filters[key]);
        isValid = isValid && user[key] == filters[key];
        
      }
    
      return isValid;
    });
   
    res.send(filteredUsers);
  });

good luck :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sarkar
Solution 2 Raymond Shafiee