简体   繁体   English

UnhandledPromiseRejectionWarning,如何解决?

[英]UnhandledPromiseRejectionWarning, how to fix it?

I don't know what I could be doing wrong to get this error:我不知道我做错了什么来得到这个错误:

在此处输入图像描述

I've tried different promises, await, async combinations and nothing.我尝试了不同的承诺,等待,异步组合,什么都没有。

I've tried Promise.resolve()) and also .then(function() .我试过Promise.resolve())和 .then .then(function()

Nothing stopped that error, what can I change to fix it?没有什么能阻止这个错误,我可以改变什么来修复它?


@Controller()
export class AppController {


    constructor(private httpSoap: HttpClient,
        @InjectModel('product') private readonly productModel: Model<any>,
        private xmlUtils: XmlUtils) { }

    @EventPattern("next")
   async handleMessagePrinted(data: Record<any, any>) {
    let result =  data;
     this.createproduct(result);
     this.insertproduct(result);
    }

    insertproduct(data: any) {
    stringify(data);
       this.productModel.insertMany(data);
      
      }

    async createproduct(job: any): Promise<any> {
        return new Promise((async (resolve, reject) => {
            // if (this.soapService.productCreate) {
            const payload = job;
            const xmlPayload = this.xmlUtils.parseJSONtoXML(payload);
           this.insertproduct(stringify(xmlPayload));  //gravar na mongo
            console.log("xmlPayload "+xmlPayload);
            const headerRequest = {
                'Content-Type': ContentTypeEnum.XML,
                SOAPAction: SoapActionEnum.CREATE_SERVICE_product
            };

            const soap: ResponseInterface = await this.request("localhost:8080", xmlPayload, headerRequest, SoapType.product);

           if (soap.error) {
                reject(soap.error);
            }
            if (soap.status) {
                if (soap.status.firewall.code === '000-000' || soap.status.firewall.code === '000-001') {
                    resolve(`product ${soap.body.Number} created successfully`);
                } else if (soap.status.firewall.code === '000-998' && soap.status.fireWall.code === '623') {
                    reject({ error: soap.status.fireWall.description });
                } else if (soap.status.firewall.code === '000-500' && soap.status.fireWall.code === 'BWENGINE-100029') {
                    const payloadSearch: productSearchDocument = new productSearchDocument();
                    payloadSearch.IsOperational = undefined;
                    payloadSearch.IsHistory = undefined;
                    payloadSearch.Qualification = `id='${job.data.id_ID}'`;
                    const search = await this.searchproduct(payloadSearch);
                    if (search.status) {
                        if (search.status.firewall.code === '000-000' || search.status.firewall.code === '000-001') {
                            resolve(`product ${soap.body.Number} created successfully`);
                        }
                    } else {
                        reject({ error: search.status.firewall.description, fireWallError: soap.status.fireWall.description });
                    }
                } else {

                    reject({ error: soap.status.firewall.description, fireWallError: soap.status.fireWall.description });
                }
            }

        }));
    }


    public async searchproduct(data: any): Promise<any> {
        return new Promise((async (resolve, reject) => {
            // if (this.soapService.productSearch) {
            const payload = data;
            const xmlPayload = this.xmlUtils.parseJSONtoXML(payload);
            const headerRequest = {
                'Content-Type': ContentTypeEnum.XML,
                SOAPAction: SoapActionEnum.SEARCH_SERVICE_product
            };
            const soap: ResponseInterface = await this.request("localhost:8080", xmlPayload, headerRequest, SoapType.product);
            if (soap.error) {
                reject(soap.error);
            }
            if (soap.status) {
                if (soap.status.firewall.code === '000-000' || soap.status.firewall.code === '000-001') {
                    resolve(soap);
                } else {
                    reject({ error: soap.status.fireWall.description });
                }
            } else {
                reject({ error: soap });
            }

        }));
    }


    public request(uri: string, data: any, headers: IHeaders, type: SoapType): Promise<any> {
        return new Promise(((resolve) => {
            this.httpSoap.request(uri, data, (async (err, res) => {
                if (err) {
                    resolve({ error: err });
                } else {
                    try {
                        console.log("fireWall response: "+data);
                        const bodyJson = await this.xmlUtils.formatXmlToJson(res.body);
                        const status: StatusInterface = await this.xmlUtils.formatStatusXML(bodyJson);
                        let body;
                        if (type === SoapType.product) {
                            body = await this.xmlUtils.formatproductServiceBodyXml(bodyJson);
                            this.insertproduct(stringify(bodyJson));  //gravar na mongo
                        } else if (type === SoapType.UNAVAILABILITY) {
                            body = await this.xmlUtils.formatImpactServiceBodyToXML(bodyJson);
                        } else if (type === SoapType.TASK) {
                            body = await this.xmlUtils.formatTaskServiceBodyXML(bodyJson);
                        } else {
                            body = '';
                        }
                        const response: ResponseInterface = {
                            status,
                            body,
                        };
                        
                        resolve(response);

                    } catch (e) {
                        resolve(e);
                    }

                }
            }), headers);
        }));
    }

    public simpleRequest(connection, payload): Promise<any> {
        return new Promise<any>((resolve, reject) => {
            const headers = {
            };
            this.httpSoap.request("localhost:8080", payload, (async (err, res) => {
                if (err) {
                    resolve({ error: err });
                } else {
                    try {
                        if (res.statusCode === 500) {
                            // const bodyJson = await this.xmlUtils.formatXmlToJson(res.body);
                            resolve(res.body);
                        } else {
                            const bodyJson = await this.xmlUtils.formatXmlToJson(res.body);
                            resolve(bodyJson);
                        }
                    } catch (e) {
                        reject(e);
                    }
                }
            }), headers);
        });
    }
}

My goal is to be able to save to mongo and also be able to make the http call to the SOAP api我的目标是能够保存到 mongo 并且能够使 http 调用 SOAP api

This warning is shown when you don't add a rejection handler to a Promise, and it's rejected.当您未将拒绝处理程序添加到 Promise 时会显示此警告,并且它会被拒绝。 It can be rejected when an error is occurred inside a promise, or reject() is called.当 promise 内部发生错误或调用reject()时,可以拒绝它。

reject called:拒绝调用:

const aa = new Promise((resolve, reject) => {
    reject(new Error('whoops'));
});

aa.then(v => {
  console.log(v);
});

// Running this script gives unhandled rejection warning

an error is occurred:发生错误:

const aa = new Promise((resolve, reject) => {
    const a = {};
    // "cannot read property 'unexistingProperty' of undefined" error is thrown here  
    const b = a.b.unexistingProperty; 
    // alternatively, when an is thrown with throw 
    // throw new Error('oops')
});

aa.then(v => {
  console.log(v);
});

// Running this script also gives unhandled rejection warning

You can add a rejection handler via then (the second argument to then() is rejection handler) or catch.您可以通过then (then() 的第二个参数是拒绝处理程序)或 catch 添加拒绝处理程序。 For async/await you can add a try/catch block to catch error.对于 async/await,您可以添加一个 try/catch 块来捕获错误。

In node.js you can also add rejection handler to all unhandled rejected promises with process.on('unhandledRejection') like this:在 node.js 中,您还可以使用process.on('unhandledRejection')将拒绝处理程序添加到所有未处理的拒绝承诺,如下所示:


process.on('unhandledRejection', error => {
    console.log(error); 
});

You can also see where the error is thrown with unhandledRejection event handler shown above, or you can run node.js with --trace-warnings like this.您还可以使用上面显示的 unhandledRejection 事件处理程序查看错误在哪里引发,或者您可以像这样使用--trace-warnings运行 node.js。

node --trace-warnings index.js

References:参考:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何修复 UnhandledPromiseRejectionWarning: TypeError? - How to fix UnhandledPromiseRejectionWarning: TypeError? 如何修复控制台中的“UnhandledPromiseRejectionWarning” - How to fix 'UnhandledPromiseRejectionWarning' in console 我该如何解决? UnhandledPromiseRejectionWarning - how do i fix this? UnhandledPromiseRejectionWarning 如何修复“UnhandledPromiseRejectionWarning:ReferenceError:内容未定义” - How to fix “UnhandledPromiseRejectionWarning: ReferenceError: content is not defined” 我如何修复节点 UnhandledPromiseRejectionWarning - How do i fix the node UnhandledPromiseRejectionWarning 如何修复 UnhandledPromiseRejectionWarning:错误:读取 ETIMEDOUT 和 UnhandledPromiseRejectionWarning:错误:写入 EPROTO 错误 - How do I fix UnhandledPromiseRejectionWarning: Error: read ETIMEDOUT and UnhandledPromiseRejectionWarning: Error: write EPROTO errors 我该如何修复(节点:5796)UnhandledPromiseRejectionWarning:错误[ERR_HTTP_HEADERS_SENT]:错误? - How can i fix (node:5796) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: error? 如何修复 UnhandledPromiseRejectionWarning: CastError: Cast to number failed for value "undefined" at Discord.js 和 MongoDB - How to fix UnhandledPromiseRejectionWarning: CastError: Cast to number failed for value "undefined" at path in Discord.js and MongoDB 如何处理`UnhandledPromiseRejectionWarning` - How to handle `UnhandledPromiseRejectionWarning` 如何避免节点中的 UnhandledPromiseRejectionWarning - How to avoid UnhandledPromiseRejectionWarning in Node
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM