gpt4 book ai didi

javascript - 尝试/捕获不捕获快速异步功能中的所有错误?

转载 作者:行者123 更新时间:2023-12-03 08:18:54 26 4
gpt4 key购买 nike

我有以下代码。

但是,它并不能捕获所有错误,而我仍然会收到“throw er;//未处理的'错误'事件”。

为什么是这样?

app.post('/api/properties/zip/:zip/bedrooms/:bedrooms', async (req, res, next) => {
try {
const file = await apiCall(req.params.zip, req.params.bedrooms);
const records = await parse(file);
const seq = await sequelize();
const result = await dbImport(seq, records);
return await res.status(200).json(`${result.length} properties successfully imported to the database`);
} catch (err) {
return next(err);
}
});

// Middleware error handling
app.use((err, req, res, next) => {
console.error(err.message);
if (!err.statusCode) err.statusCode = 500;
return res.status(err.statusCode).json(err.message);
});

例如,直到我添加了特定的错误处理程序,它才在parse()函数中捕获错误。我的try/catch是否不添加此错误也不会捕获此错误?
const fs = require('fs');

const parse = filename => new Promise(((resolve, reject) => {
// Converts a line from the file, parses it to JSON, and stores it an array
const func = (data, records) => {
const json = JSON.parse(data);
records.push(json);
};

// Read in each line of the file and pass that line to func
const readLines = (input) => {
const records = [];
let remaining = '';


// ******** HAD TO ADD THIS *********
input.on('error', (err) => {
reject(err);
});


input.on('data', (data) => {
remaining += data;
let index = remaining.indexOf('\n');
let last = 0;
while (index > -1) {
const line = remaining.substring(last, index);
last = index + 1;
func(line, records);
index = remaining.indexOf('\n', last);
}
remaining = remaining.substring(last);
});

input.on('end', () => {
if (remaining.length > 0) {
func(remaining, records);
}
resolve(records);
});
};

const input = fs.createReadStream(filename);
readLines(input, func);
}));

module.exports = parse;

提前致谢!

最佳答案

也许这将为您演示使用await时try/catch的工作方式。当一个 promise 是rejected时,它将throw得到的值。如果底层 promise resolves,它将返回该值。

(async () => {
try {
const val1 = await Promise.resolve('resolved val');
const val2 = await Promise.reject('reject val');
console.log(val1);
} catch (err) {
console.error(err);
}
})();

关于javascript - 尝试/捕获不捕获快速异步功能中的所有错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62013990/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com