簡體   English   中英

UnhandledPromiseRejectionWarning,Express.js和Node.js

[英]UnhandledPromiseRejectionWarning, Express.js and Node.js

我對Node.jsExpress.js完全陌生,並且一直在嘗試通過一些示例將Shippo API集成到我的電子商務Web應用程序中,但是我遇到了一些錯誤,盡管檢查了一下我還是無法解決代碼幾次。

我收到UnhandledPromiseRejectionWarning錯誤,從我在線閱讀的內容中,這意味着我的代碼中某處有一個.then()節,其中不包含“捕獲”或“要做的事情”,這是請求返回的內容一個錯誤。 任何幫助將不勝感激。

這是我的代碼:

 var express = require('express') var app = express() var http = require('http'); var Raven = require('raven'); var shippo = require('shippo')('ACCESS_TOKEN'); var engines = require('consolidate'); const bodyParser = require('body-parser'); const path = require('path'); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); app.engine('html', engines.mustache); app.set('view engine', 'html'); //app.use(express.static(path.join(_dirname,'/'))); app.get('/', function (req, res) { res.render('Index.html'); }) app.post('/', function (req, res) { var addressFrom = { "object_purpose":"PURCHASE", "name": "SENDER_NAME", "company":"Shippo", "street1":"215 Clayton St.", "city":"San Francisco", "state":"CA", "zip":"94117", "country":"US", //iso2 country code "phone":"+1 555 341 9393", "email":"SENDER_EMAIL", }; // example address_to object dict var addressTo = { "object_purpose":"PURCHASE", "name": req.body.fnames + ' ' + req.body.lnames, "company": req.body.company, "street1":req.body.street, "city":req.body.city, "state":req.body.state, "zip":req.body.zipcode, "country": req.body.country, //iso2 country code "phone":"+1 555 341 9393", "email":"support@goshippo.com", }; // parcel object dict var parcelOne = { "length":"5", "width":"5", "height":"5", "distance_unit":"in", "weight":"2", "mass_unit":"lb" }; var shipment = { "object_purpose": "PURCHASE", "address_from": addressFrom, "address_to": addressTo, "parcels": [parcelOne], "submission_type": "DROPOFF" }; shippo.transaction.create({ "shipment": shipment, "servicelevel_token": "ups_standard", "carrier_account": 'CARRIER_TOKEN', "label_file_type": "PDF" }) .then(function(transaction) { shippo.transaction.list({ "rate": transaction.rate }) .then(function(mpsTransactions) { mpsTransactions.results.forEach(function(mpsTransaction){ if(mpsTransaction.object_status == "SUCCESS") { console.log("Label URL: %s", mpsTransaction.label_url); console.log("Tracking Number: %s", mpsTransaction.tracking_number); console.log("E-Mail: %s", mpsTransaction.object_owner); console.log(mpsTransaction.object_status); res.status(200).send("Label can be found under: " + mpsTransaction.label_url); } else { // hanlde error transactions console.log("Message: %s", mpsTransactions.messages); } }); }) }, function(err) { // Deal with an error console.log("There was an error creating transaction : %s", err.detail); res.send("something happened :O") }); }) app.post('/successp', function (req, res) { var token = req.body.stripeToken; // Using Express // Charge the user's card: var charge = stripe.charges.create({ amount: 1000, currency: "eur", description: "Example charge", source: token, }, function(err, charge) { // asynchronously called }); res.send('Thanks!') }) app.post('/successp', function (req, res) { var token = req.body.stripeToken; // Using Express // Charge the user's card: var charge = stripe.charges.create({ amount: 1000, currency: "eur", description: "Example charge", source: token, }, function(err, charge) { // asynchronously called }); res.send('Thanks!') }) app.listen(3000, function () { console.log('Example app listening on port 3000!') }) 

這是我得到的錯誤:

在端口3000上監聽的示例應用程序! (節點:2378)UnhandledPromiseRejectionWarning(節點:2378)UnhandledPromiseRejectionWarning:未處理的承諾拒絕。 引發此錯誤的原因可能是拋出了一個沒有catch塊的異步函數,或者是拒絕了一個.catch()無法處理的承諾。 (拒絕ID:1)(節點:2378)[DEP0018] DeprecationWarning:已棄用未處理的承諾拒絕。 將來,未處理的承諾拒絕將以非零退出代碼終止Node.js進程。

我也不完全確定某些代碼行的用途(再次,我對表示和node.js非常陌生)。 什么是引擎和胡須? 另外,我看到此示例代碼使用APP.POST('/ succesp',function(req,res)...)'/ succesp'到底是什么? 我需要創建另一個HTML文件嗎? 另外, 開頭的app.use(express.statc([ath.join(_dirnam,'/')));;) ”是什么?

你需要使用的格式小心一點then(FN, errorFn)因為如果有內部的錯誤then ,該errorFn不會趕上它。 最好使用then(fn).catch(errorFn) 這將允許在任何所有的錯誤then上面向下篩選到最后catch處理。

例如,第一個調用正確捕獲了錯誤,而第二個則沒有:

 function fn() { return Promise.resolve("good") } fn() .then(r => { throw ("whoops") }) .catch(err => console.log(err)) //<-- catch works here fn() .then(r => { throw ("whoops") }, err => console.log(err) // this can't catch the error above; it will only catch rejections on fn() ) 

它沒有顯示在代碼段中,但是如果您查看控制台,則會看到未處理的拒絕錯誤。

在您的代碼中,可以通過從shippo.transaction.list返回承諾來shippo.transaction.list承諾鏈。 然后,您可以在末尾添加一個catch以處理錯誤。

shippo.transaction.create({
    "shipment": shipment,
    "servicelevel_token": "ups_standard",
    "carrier_account": 'CARRIER_TOKEN',
    "label_file_type": "PDF"
})
.then(function(transaction) {
    return shippo.transaction.list({  // return this promise
    "rate": transaction.rate
})
.then(function(mpsTransactions) {     // so this can flatten out
    mpsTransactions.results.forEach(function(mpsTransaction){
        if(mpsTransaction.object_status == "SUCCESS") {
            console.log("Label URL: %s", mpsTransaction.label_url);
            console.log("Tracking Number: %s", mpsTransaction.tracking_number);
            console.log("E-Mail: %s", mpsTransaction.object_owner);
            console.log(mpsTransaction.object_status);
            res.status(200).send("Label can be found under: " + mpsTransaction.label_url);
        } else {
            // hanlde error transactions
            console.log("Message: %s", mpsTransactions.messages);
        }
    });
})
.catch(function(err) {   // catch errors
    // Deal with an error
    console.log("There was an error creating transaction : %s", err.detail);
    res.send("something happened :O")
});
})

由於很難在沒有所有內容的情況下在本地運行,因此我對錯誤的來源並res.status(200).send() ,但是看起來您正在循環內發送res.status(200).send() ,這可能會導致如果它被調用兩次,則會出錯。

如果不閱讀完整的代碼,則在使用Promises時不應嘗試使用回調函數捕獲錯誤。 您使用.catch塊捕獲Promises中的錯誤

並且您還應該返回第一個承諾,以便將其傳遞給下一個.then函數(如果您打算將shippo.transaction.list作為mpsTransactions返回)

像這樣:

 shippo.transaction.create({
 "shipment": shipment,
 "servicelevel_token": "ups_standard",
 "carrier_account": 'CARRIER_TOKEN',
 "label_file_type": "PDF"
})
  .then(function(transaction) {
      return shippo.transaction.list({
        "rate": transaction.rate
      })
   })
  .then(function(mpsTransactions) {
    mpsTransactions.results.forEach(function(mpsTransaction){
        if(mpsTransaction.object_status == "SUCCESS") {
            console.log("Label URL: %s", mpsTransaction.label_url);
            console.log("Tracking Number: %s", mpsTransaction.tracking_number);
            console.log("E-Mail: %s", mpsTransaction.object_owner);
            console.log(mpsTransaction.object_status);
            res.status(200).send("Label can be found under: " + mpsTransaction.label_url);
        } else {
            // hanlde error transactions
            console.log("Message: %s", mpsTransactions.messages);
        }
    });
   })
  .catch(function (error) {
    // Deal with an error
    console.log("There was an error creating transaction : %s", err.detail);
    res.send("something happened :O")
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM