Saturday 22 April 2017

How to Handle ES7 - Unhandled promise rejection in async object method in Node.js expressjs?

Im using the async function inside the object to send a response in express.js

Controller Code :

module.exports = {

    async signUpEmail(req, res) {

        /**
         * @description Parameters from body
         * @param {string} firstName - First Name
         * @inner
         */  

        const firstName = req.body.firstName;

        res.send({ success: name });
        throw new Error(); // purposely Done
    }
}

Question:

Since the signUpEmail method is async in my case and it will get rejected with whatever my async method throw's here it's comes Error.(purposely put there)

so getting this logged in the console.

(node:13537) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error
(node:13537) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

So i'm supposed to handle it from the routes from where i'm calling it.

Router Code

    const routes = require('express').Router();
const SignUpController = require('../controllers/signUpController')

// /signup
routes.post('/', SignUpController.signUpEmail);

module.exports = routes;

some what like this SignUpController.signUpEmail().then(…); But since i'm not calling function in the routes i'm just passing. How this can be done effectively ?

PS:Please Don't suggest too complicated solutions. I'm beginner with JS and is learning through.

I Didn't use chainable route handlers because i want to create modular, mountable route handler.

Official Doc Example - http://expressjs.com/en/guide/routing.html#express.Router



via Ankur Anand

No comments:

Post a Comment