Mongoose / Typescript - UnhandledPromiseRejectionWarning, когда присутствует catch - PullRequest
0 голосов
/ 26 мая 2018

Я не уверен, почему я вижу это предупреждение UnhandledPromiseRejection.В этом коде '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 голосов
/ 26 мая 2018

Вы в основном

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);
});
0 голосов
/ 26 мая 2018

catch ловит ошибку от promise, но не promise.then(...).Если в then возникнет ошибка, это приведет к необработанному отклонению.Даже если оно не выброшено, а передано из promise, в этом обещании оно считается невыполненным.

Оно должно быть:

promise
.then((requirement) => {
    return res.json(requirement);
})
.catch((reason) => {
    let err = {'error': reason};
    return res.json(err);
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...