如何在Chrome中捕获DOMException?

Jac*_*hal 9 javascript google-chrome screen-orientation domexception

我收到此错误:

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

当我在Chrome中运行以下代码时:

try {
  screen.orientation.lock('portrait');
} catch (error) {
  // whatever
}
Run Code Online (Sandbox Code Playgroud)

由于桌面Chrome不支持方向锁定,因此预计会抛出错误.我想捕获错误,所以它不会乱丢控制台,但将它包装在一个try...catch块中似乎不起作用.

为什么我不能抓住它?我错过了什么吗?

Ale*_*ara 18

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

未捕获(在promise中)DOMException:此设备上没有lockOrientation().

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

screen.orientation.lock('portrait').catch(function(error) {
    // whatever
});
Run Code Online (Sandbox Code Playgroud)