猫鼬/打字稿 - 存在捕获时未处理的承诺拒绝警告 [英] Mongoose/Typescript - UnhandledPromiseRejectionWarning when catch is present

查看:54
本文介绍了猫鼬/打字稿 - 存在捕获时未处理的承诺拒绝警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm not sure why I'm seeing this UnhandledPromiseRejectionWarning. In this code, 'id' is a Mongoose Index, and I am testing inserting a duplicate ID which should be handled properly.

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,所以我知道我的拒绝处理程序正在执行:

In fact, the following JSON is returned, so I know my rejection handler is executing:

{
    "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\" }"
    }
}

我看到的确切警告如下:

The exact warnings I'm seeing are the following:

(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.

推荐答案

catchpromise 但不是 promise.then(...).如果在 then 中抛出错误,这将导致未处理的拒绝.即使它不是抛出而是从 promise 传播的,它也被认为在这个 Promise 中未被捕获.

catch catches an error from promise but not promise.then(...). If an error is thrown inside then, this would result in unhandled rejection. Even if it's not thrown but is propagated from promise, it is considered uncaught in this promise.

应该是:

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

这篇关于猫鼬/打字稿 - 存在捕获时未处理的承诺拒绝警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆