I am trying to handle error with class constructor in a better way. I named my class HttpError that is written below, the problem is HttpError doesn't work properly.
This is "app.js" file:
const express = require('express');
const app = express();
const placesRoutes = require('./routes/placesRoutes');
app.use('/api/places',placesRoutes);
app.get('/', (req, res, next) => {
res.json({message: 'the server is working.'});
next();
});
app.use((error, req, res, next)=> {
if(res.headerSent){
return next(error);
}
res.status(error.code || 500);// This error shows when I am entering wrong pid
res.json({message: 'Does not match any route'});
})
app.listen(5000);
and this is placesRoutes.js:
const express = require('express');
const HttpError = require('../models/httpError');
const router = express.Router();
const DUMMY_PLACE = [
{
id: '1',
name: 'jahid',
address: 'Rajoir, Rayenda, Sarankhola, Bagerhat',
email: 'gahid@gmail.com',
password: 'jahid5868'
},
{
id: '2',
name: 'saiful',
address: 'Rajoir, Rayenda, Sarankhola, Bagerhat',
email: 'gahid@gmail.com',
password: 'jahid5868'
},
{
id: '3',
name: 'sadiqul',
address: 'Rajoir, Rayenda, Sarankhola, Bagerhat',
email: 'gkaid@gmail.com',
password: 'jahid5868'
},
{
id: '4',
name: 'hasib',
address: 'Rajoir, Rayenda, Sarankhola, Bagerhat',
email: 'ahid@gmail.com',
password: 'jahid5868'
},
]
router.get('/:pid', (req, res, next) => {
const sid = req.params.pid;
const data = DUMMY_PLACE.find(p=> p.id === sid);
if(!data){
return next(new HttpError('Does not found uid', 404));
}
res.json({data});
});
module.exports = router;
and this is "HttpError.js":
class HttpError extends Error {
constructor(message, statusCode) {
super();
this.message = message;
this.statusCode = statusCode;
}
};
module.exports = HttpError;
When I am entering /api/places/:(wrong-pid). It doesn't show HttpError rather it's showing the error 500 from bottom of app.js. I am new to express so please don't bother if my question doesn't make sense.