F
F
frontendo2017-08-30 19:54:32
Node.js
frontendo, 2017-08-30 19:54:32

How to make single point error handling in expressjs application?

There is a simple express application built on the principles of mvc, here is a piece of code from the router

const router = require('express').Router();
const Auth = require('./controllers/AuthController');

router.post('/register', Auth.register);
router.post('/login', Auth.login);
router.post('/current-user', Auth.getCurrentUser);
router.post('/forgot-password', Auth.forgotPassword);
router.post('/reset-password', Auth.resetPassword);

module.exports = router;

Accordingly, a controller is a module that returns an object with methods. In each method there is a call to models (so far from 1 to 3 requests), everything is built on async / await
Here, for example, one of the methods
register: async (req, res) => {
    validator.checkEmail(req.body.email);

    if (!validator.errorLength)
      await validator.checkEmailNotExist(req.body.email);

    validator.checkPassword(req.body.password, req.body.password_confirm || '');

    if (validator.errorLength)
      return res.sendInputsErrors(validator.getAndCleanErrors());

    try {
      let user = await User.create({
        email: req.body.email,
        password: crypt.hash(req.body.password)
      });

      auth.sendSuccessAuthenticatedResponse(user, req, res);
    } catch (e) {
      res.sendServerError(e)
    }

    return true;
  }

So, I would like to get rid of these ubiquitous try...catch, as I understand it, that theoretically, this construction should wrap the place where the route handler is called

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question