How to handle error in express with class?

Viewed 456

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.

2 Answers

With the above code an instance of HttpError gets passed to the error handling middleware, but you do not really use it there. You probably wanted to do something like:

app.use((error, req, res, next)=> {
    if(res.headerSent){
        return next(error);
    }
    if(error instanceof HttpError) {
      res.status(error.statusCode);
      res.json({message: error.message});
    } else {
      res.status(error.code || 500);
      res.json({message: 'Does not match any route'});
    }
})

So basically you have many ways of handling Errors, I like to use try/catch blocks very simple to understand and very useful and clear. You're doing a block asking him to do something if it's getting an error it's passing it to the catch block.

For example:

const validateUser = async (req, res, next) => {
  try {
    const { email, password } = req.body
    if (!email || !password) {
      throw new ErrorHandler(404, 'Missing required email and password fields')
    }
    const user = await  db.User.findOne({ where: { email }});
    if (!user) {
      throw new ErrorHandler(404, 'User with the specified email does not exists')
    }
    next()
  } catch (error) {
    next(error)
  }
}

so we try something (getting data checking it) if there is an error its passing to the catch block.

another simplest example:

try {
      capture = await payPalClient.client().execute(request);
      captureID = capture.result;
      // console.log(captureID)
    } catch (err) {
      // 4. Handle any errors from the call
      return res.status(500).send({
        status: 500,
        error: err,
      });
    }

trying something (some paypal stuff from one of my code not important). if I'm getting an error from it I return a response (500 with a message of error .)

you can check on google for error handling express try/catch

Related