javascript 如何在 Chrome 中捕获 DOMException?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31509619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to catch DOMException in Chrome?
提问by Hyman Senechal
I get this error:
我收到此错误:
Uncaught (in promise) DOMException: lockOrientation() is not available on this device.
code: 9
message: "lockOrientation() is not available on this device."
name: "NotSupportedError"
when I run the following code in Chrome:
当我在 Chrome 中运行以下代码时:
try {
screen.orientation.lock('portrait');
} catch (error) {
// whatever
}
The fact that the error is being thrown is expected, since Desktop Chrome doesn't support orientation locking. I'd like to catch the error so it doesn't litter the console, but wrapping it in a try...catch
block doesn't seem to work.
预计会抛出错误,因为桌面 Chrome 不支持方向锁定。我想捕获错误,这样它就不会乱扔控制台,但是将它包装在一个try...catch
块中似乎不起作用。
Why can't I catch it? Am I missing something?
为什么我抓不到?我错过了什么吗?
回答by Alexander O'Mara
try/catch
does not work here, because screen.orientation.lock('portrait');
actually returns a Promisewhich is throwing the error. This part of the error shows the exception is thrown in the promise.
try/catch
在这里不起作用,因为screen.orientation.lock('portrait');
实际上返回了一个抛出错误的Promise。这部分错误说明promise中抛出了异常。
Uncaught (in promise) DOMException: lockOrientation() is not available on this device.
Uncaught (in promise) DOMException: lockOrientation() 在这个设备上不可用。
To handle the exception, you can attach a catch
callback.
要处理异常,您可以附加catch
回调。
screen.orientation.lock('portrait').catch(function(error) {
// whatever
});