Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Handle 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

like image 427
Ankur Anand Avatar asked Apr 22 '17 20:04

Ankur Anand


People also ask

How do you deal with unhandled promise rejection?

If an error condition arises inside a promise, you “reject” the promise by calling the reject() function with an error. To handle a promise rejection, you pass a callback to the catch() function.

Why do I get an unhandled promise rejection with await promise all?

This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .

What happens on unhandled promise rejection?

The unhandledrejection event is sent to the global scope of a script when a JavaScript Promise that has no rejection handler is rejected; typically, this is the window , but may also be a Worker . This is useful for debugging and for providing fallback error handling for unexpected situations.

How do you handle reject In await?

Handling rejected promises You can handle rejected promises without a try block by chaining a catch() handler before awaiting the promise.


1 Answers

In your route, you will need to add a wrapper to catch thrown errors:

let wrapper = fn => (...args) => fn(...args).catch(args[2]);

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

With this method you can use a top level error catcher and do not need to use internal try catch blocks in your routes, unless you need to them contextually.

Use error catching middleware to achieve this as follows:

// last middleware in chain

app.use(function(err, req, res, next) {
    // handle your errors
});

Now in your routes you can throw errors and they will be caught by that middleware. I like to throw custom errors and handle their response and logging in this middleware.

Aside: The async await pattern is great for writing asynchronous code that is easy for a human to read in a synchronous fashion. Just remember that once you go async, you should stay async! Using a promisification library such as Bluebird and invoking .promisifyAll on nodeback libraries is highly recommended.

EDIT : Source - Asynchronous Error Handling in Express with Promises, Generators and ES7

like image 157
Kyle Richardson Avatar answered Oct 11 '22 14:10

Kyle Richardson