LoginSignup
5
2

More than 3 years have passed since last update.

window.onerror を Chrome の Developer console で発火させる方法

Last updated at Posted at 2019-09-05

window.onerror

window.onerror とは、処理を設定しておくことで UI 処理全体の Uncaught Error (catch されなかった error) を catch することができます。Global (ブラウザの window 全体) の Error handling です。

window.onerror = function(errorMessage, filePath, rowNumber, columnNumber, errorObject) {
    alert(errorMessage);
};

Chrome の Developer console で試してみる

Chrome の Developer console を開いて以下のように window.error を定義し、Error を throw してみます。

window.onerror = function() {
  alert('Error has occurred!');
}

throw new Error('Boom!');
> Uncaught Error: Boom!
    at <anonymous>:1:7

alert dialog が出ませんでした... :thinking:

これは、同期処理に関しては Global にではなく、Developer console 内でエラー処理を完結しようとしているからのようです。
逆に言うと、window.onerror を発火させるためには非同期処理でエラーを起こせば良いと言うこと。

setTimeout を使って非同期にする

setTimeout は ms (1/1000 秒) なので、1秒後に Error を throw してみます。

window.onerror = function() {
  alert('Error has occurred!');
}

setTimeout(function() { throw new Error('Boom!') }, 1000);

.....
スクリーンショット 2019-09-05 18.25.34.png
出ました! :tada: :tada:

思えば、Node.js でも以下のように同期処理だったら、もちろん throw した Error を catch してくれますが、

// err_test.js

try {
  throw new Error('Error has occurred!');
} catch(e) {
  console.log(e);
} 
$ node err_test.js
> Error: Error has occurred!

非同期処理にすると、node の Context(環境) を突き抜けて Shell が status code 1 を返していました。

// err_test.js

try {
  setTimeout(function() { throw new Error('Error has occurred!'); }, 1000);
} catch(e) {
  console.log(e);
}
$ node err_test.js
err_test.js:3
  setTimeout(function() { throw new Error('Error has occurred!'); }, 1000);
                          ^
shell returned 1

ある Context を逸脱し、それを包含しているより広い Context 影響を与えるには、非同期処理というのが一つキーポイントになるようです :thinking:

※ Node.js の件に関してはこの記事がとても勉強になりました。
https://techblog.yahoo.co.jp/programming/javascript_error/

おまけ

非同期処理で Context を逸脱しなくても、ブラウザのアドレスバーに以下のように直接入力し、Grobal の Error handling を発火させるという荒技もあるようです。

javascript: throw New Error('Error has occurred!');
5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2