gpt4 book ai didi

node.js - 如何处理 node.js 请求中的 URI 错误?

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

尝试简单地下载带有请求的文件。 https://www.npmjs.com/package/request

它工作得很好,但如果 url 无效,脚本会崩溃并出现错误:Invalid URI "notagoodurl"

如何处理此错误并记录某些内容并防止整个脚本因此错误而结束?我认为这就是 on('error') 会做的。

//download file
request
.get(url)
.on('error', function(err) {
return err;
})
.pipe(
fs.createWriteStream(destination)
.on('close', function() {
message.channel.send(filename + ' added.');
})
);

最佳答案

如果您需要解决 fatal error ,请将调用包装到 catch :

try {
//download file
request
.get(url)
.on('error', function(err) {
console.log('Not a fatal error:', err);
})
.pipe(
fs.createWriteStream(destination)
.on('close', function() {
message.channel.send(filename + ' added.');
})
);
} catch (err) {
console.log('Fatal error:', err);
}

关于node.js - 如何处理 node.js 请求中的 URI 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49786532/

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