8

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

4

1 回答 1

8

在您的路线中,您需要添加一个包装器来捕获抛出的错误:

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

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

使用此方法,您可以使用顶级错误捕获器,并且不需要在路由中使用内部 try catch 块,除非您需要根据上下文使用它们。

使用错误捕获中间件来实现这一点,如下所示:

// last middleware in chain

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

现在,在您的路由中,您可以抛出错误,它们将被该中间件捕获。我喜欢抛出自定义错误并处理它们的响应并登录这个中间件。

旁白:异步等待模式非常适合编写易于人类以同步方式阅读的异步代码。请记住,一旦你去异步,你应该保持异步!强烈建议使用诸如 Bluebird 之类的 Promisification 库并调用.promisifyAllnodeback

编辑:Source - Express 中的异步错误处理与 Promises、Generators 和 ES7

于 2017-04-22T20:30:48.977 回答