当catch存在时,Mongoose / Typescript - UnhandledPromiseRejectionWarning

时间:2018-05-26 19:53:31

标签: javascript typescript promise

我不确定为什么我会看到这个UnhandledPromiseRejectionWarning。在此代码中,' id'是一个Mongoose索引,我正在测试插入一个应该正确处理的重复ID。

router.post('/create/:id', jsonParser, (req: Request, res: Response) => {
    let { id } = req.params;
    if (!req.body) {
        return res.sendStatus(400)
    }

    // @TODO add validation on JSON
    let promise = Requirement.create({id: id, data: req.body.data, deleted: false});

    promise.then((requirement) => {
        return res.json(requirement);
    });

    promise.catch((reason) => {
        let err = {'error': reason};
        return res.json(err);
    });
});

实际上,返回了以下JSON,所以我知道我的拒绝处理程序正在执行:

{
    "error": {
        "name": "MongoError",
        "message": "E11000 duplicate key error collection: rex.requirements index: id_1 dup key: { : \"REQ001\" }",
        "driver": true,
        "index": 0,
        "code": 11000,
        "errmsg": "E11000 duplicate key error collection: rex.requirements index: id_1 dup key: { : \"REQ001\" }"
    }
}

我看到的确切警告如下:

(node:11408) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: E11000 duplicate key error collection: rex.requirements index: id_1 dup key: { : "REQ001" }
(node:11408) [DEP0018] 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.

2 个答案:

答案 0 :(得分:0)

catchpromise但未promise.then(...)收到错误。如果在then内引发错误,则会导致未处理的拒绝。即使它没有被抛出但是从promise传播,它也被认为没有被承诺。

应该是:

promise
.then((requirement) => {
    return res.json(requirement);
})
.catch((reason) => {
    let err = {'error': reason};
    return res.json(err);
});

答案 1 :(得分:0)

你基本上做了

var a = promise.then(…);
var b = promise.catch(…);

在链中创建分支。如果promise现在被拒绝,则catch回调将被调用,而b将是一个已履行的承诺就好了,但a承诺也会被拒绝,并且无人处理这一点。

相反,您应该使用then的两个参数并写入

Requirement.create({id: id, data: req.body.data, deleted: false})
.then(requirement => {
    res.json(requirement);
}, reason => {
    let err = {'error': reason};
    res.json(err);
});