How to handle raw promise rejection in an async object method in Node.js expressjs?

Im using the async function inside an 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 asynchronous in my case, and it will be rejected with any of my async methods, it returns Error . (intentionally placed)

so go to 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 have to process it from the routes where I call it from.

Router Code

  const routes = require('express').Router(); const SignUpController = require('../controllers/signUpController') // /signup routes.post('/', SignUpController.signUpEmail); module.exports = routes; 

something like this SignUpController.signUpEmail().then(…); But since I do not call the function in the routes that I just go through. How can this be done effectively ?

PS: Please do not offer too complicated solutions. I start with JS and study.

I did not use attached route handlers because I want to create a modular, mounted route.

Official Doc Example

+5
source share
1 answer

In your route you will need to add a shell to catch the abandoned errors:

 let wrapper = fn => (...args) => fn(...args).catch(args[2]); // /signup routes.post('/', wrapper(SignUpController.signUpEmail)); 

With this method, you can use the top-level error trap and you do not need to use catch catch blocks in your routes, unless you need them contextually.

Use middleware to detect errors to achieve this as follows:

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

Now you can throw errors on your routes and they will be caught by this middleware. I like to throw user errors and process their response and log in to this middleware.

In addition: an asynchronous wait pattern is great for writing asynchronous code that a person reads easily synchronously. Just remember that as soon as you go asynchronously, you must remain asynchronous! It is recommended that you use a promisification library such as Bluebird and use .promisifyAll in the nodeback libraries.

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

+4
source

Source: https://habr.com/ru/post/1267055/


All Articles