13

我收到此错误:

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 不支持方向锁定,因此会引发错误这一事实是意料之中的。我想捕捉错误,这样它就不会乱扔控制台,但将它包装在一个try...catch块中似乎不起作用。

为什么我抓不到?我错过了什么吗?

4

1 回答 1

25

try/catch在这里不起作用,因为screen.orientation.lock('portrait');实际上返回了一个抛出错误的Promise 。这部分错误表明在 Promise 中抛出了异常。

Uncaught (in promise) DOMException: lockOrientation() 在此设备上不可用。

要处理异常,您可以附加catch回调。

screen.orientation.lock('portrait').catch(function(error) {
    // whatever
});
于 2015-07-20T06:01:58.050 回答