CarlosMagalhaes
CarlosMagalhaes

Reputation: 91

UnhandledPromiseRejectionWarning, how to fix it?

I don't know what I could be doing wrong to get this error:

enter image description here

I've tried different promises, await, async combinations and nothing.

I've tried Promise.resolve()) and also .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

Upvotes: 0

Views: 182

Answers (1)

srknzl
srknzl

Reputation: 787

This warning is shown when you don't add a rejection handler to a Promise, and it's rejected. It can be rejected when an error is occurred inside a promise, or reject() is called.

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. For async/await you can add a try/catch block to catch error.

In node.js you can also add rejection handler to all unhandled rejected promises with process.on('unhandledRejection') like this:


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.

node --trace-warnings index.js

References:

Upvotes: 1

Related Questions