如何在Chrome中捕获DOMException?

ergxz8rk  于 2023-04-09  发布在  Go
关注(0)|答案(1)|浏览(229)

我得到这个错误:

Uncaught (in promise) DOMException: lockOrientation() is not available on this device.
  code: 9
  message: "lockOrientation() is not available on this device."
  name: "NotSupportedError"

在Chrome中运行以下代码:

try {
  screen.orientation.lock('portrait');
} catch (error) {
  // whatever
}

由于桌面Chrome不支持方向锁定,因此抛出错误是意料之中的。我想捕获错误,这样它就不会乱丢控制台,但将其 Package 在try...catch块中似乎不起作用。
为什么我抓不到?我错过什么了吗?

h9vpoimq

h9vpoimq1#

同步try/catch在这里不起作用,因为screen.orientation.lock('portrait');实际上返回了一个抛出错误的Promise。错误的这一部分显示异常在promise中被抛出。
Uncaught(in promise)DOMException:lockOrientation()在此设备上不可用。
要处理这个异常,可以附加一个catch回调。

screen.orientation.lock('portrait').catch(function(error) {
    console.log(error);
});

或者在异步函数中,你可以尝试/捕获一个await。

try {
    await screen.orientation.lock('portrait');
}
catch (error) {
    console.log(error);
}

相关问题