【发布时间】:2019-04-16 00:51:49
【问题描述】:
我是新来的等待。我只是不知道如何处理所有等待错误和拒绝。总是有来自 shopify-api.js 函数的未处理拒绝,我无法打印来自我创建 index.js 的中间件的所有错误?
如何打印所有错误?我在等待处理正确吗?
index.js
const functions = require('firebase-functions');
const app = require('express')();
const cors = require('cors');
// Automatically allow cross-origin requests
app.use(cors({ origin: true }));
const asyncMiddleware = fn => (req, res, next) => {
Promise.resolve(fn(req, res, next))
.catch((err) => {
console.error(err);
res.json(err)
})
.catch(next)
};
app.get('/v1/Test/Shopify', asyncMiddleware ( async (req, res, next) => {
req.params.workshopId = "TEST_CR"
req.params.date = "2018-11-30"
req.params.startTime = "11:00"
let result1 = await ShopifyWorkshop.AddDate(req, res, next)
console.log("ShopifyWorkshop.AddDate: Success" .green)
res.status(200).json({message: "Success"})
}));
exports.AddDate = async (req, res, next) => {
await Helper.CheckParamsIsNull(req.params)
let wsId = req.params.workshopId
let wsDate = req.params.date
let wsTime = req.params.startTime
// Check if workshop is a level
if (Helper.IsWorkshopType(wsId)) {
return await Promise.all(WORKSHOP_TYPE[wsId].levelNames.map( async (typeName) => {
WORKSHOP_CATEGORY[typeName].codeNames.map( async (codeName) => {
for (let wsId in WORKSHOP_INFO) {
if (WORKSHOP_INFO[wsId].codeName === codeName) {
addVariant(wsId, wsDate, wsTime)
}
}
})
}))
} else if (Helper.IsWorkshopCategory(wsId)) {
return await Promise.all(WORKSHOP_CATEGORY[wsId].codeNames.map ( async (codeName) => {
for (let wsId in WORKSHOP_INFO) {
if (WORKSHOP_INFO[wsId].codeName === codeName) {
await addVariant(wsId, wsDate, wsTime)
}
}
}))
} else {
return await addVariant(wsId, wsDate, wsTime)
}
}
shopify-api.js
exports.AddAProductVariant = async (id, options) => {
console.log("Adding variant to product..." + options.option1)
let result = await shopify.productVariant.create(id, options)
console.log("Added product variant: " + options.option1)
return result
}
【问题讨论】:
-
这是一篇很棒的文章,可能对 blog.grossman.io/… 有所帮助。有几个选项,但
try {} catch {}块是处理等待错误时最常见的。 -
但我使用了一个中间件来捕获所有错误,因此我不需要在每个函数中都使用 try/catch。我做得不对吗?对不起这个小菜鸟
-
我很抱歉我的误解:)。嗯,我需要设置它才能正确测试。这也是一篇很棒的文章,用于承诺吞咽错误等jamesknelson.com/are-es6-promises-swallowing-your-errors。
-
您不需要将
next回调传递给AddDate
标签: javascript firebase express promise async-await