环境
- 节点v19.0.0
- 应用@babel/预设字体
- 应用@babel/preset env
-
tsconfig.json
target设置为ES6
出身背景
下面的代码有一个try/catch块,如果new URL构造函数失败,我将捕获错误并使用if (err instanceof TypeError)...处理它。
问题
我面临的问题是,我一直无法让err instanceof TypeError成为现实。
我在浏览器中测试过,传递给URL()的无效URL会引发TypeErrors。
以下是console.logging我的节点环境中的一些其他观察结果:
-
err instanceof Error=>;假的 -
err instanceof TypeError=>;假的 -
console.log(err.name)=>;类型错误 -
console.log(err.message)=>;URL无效 -
console.log(err.constructor)=>;[功能:类型错误]
function getURLsFromHTML(htmlBody: string, baseURL: string) {
const urls: string[] = []
const dom = new JSDOM(htmlBody)
const linkElements = dom.window.document.querySelectorAll("a")
for (const link of linkElements) {
if (link.href.slice(0, 1) === "/") {
// relative URL
try {
const url = new URL(`${baseURL}${link.href}`)
urls.push(url.href)
}
catch (err) {
if (err instanceof TypeError) {
console.log("Err with relative url", err.message)
}
else {
console.log("Else is logged")
}
}
}
else {
// absolute
try {
const url = new URL(`${link.href}`)
urls.push(url.href)
}
catch (err) {
if (err instanceof TypeError) {
console.log("Err with absolute url", err.message)
}
else {
console.log("Could not find type of err")
}
}
}
}
return urls
}
当try/catch块中唯一可能的失败是TypeError时,为什么err没有被键入为TypeError?