How to catch DOMException in Chrome?
Asked Answered
A

1

16

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:

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.

Why can't I catch it? Am I missing something?

Austine answered 20/7, 2015 at 5:54 Comment(0)
G
32

Synchronous try/catch does not work here, because screen.orientation.lock('portrait'); actually returns a Promise which is throwing the error. This part of the error shows the exception is thrown in the promise.

Uncaught (in promise) DOMException: lockOrientation() is not available on this device.

To handle the exception, you can attach a catch callback.

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

Alternately in an async function, you can try/catch an await.

try {
    await screen.orientation.lock('portrait');
}
catch (error) {
    console.log(error);
}
Ginetteginevra answered 20/7, 2015 at 6:1 Comment(1)
Thats just what I needed, thanks! Since other implementations return true/false and Chrome returns a promise, I wrote up a gist on how to combine the various implementations into one function. gist.github.com/jacksenechal/67315945593d452407ffAustine

© 2022 - 2024 — McMap. All rights reserved.