2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JSでErrorを継承して作った独自エラークラスを判定する方法

Posted at

Errorを継承して独自のエラークラスを作る方法は以下の感じです。

class MyError extends Error {
  constructor (msg) {
    super(msg)
  }
}

try {
  // ...
  // ここでエラーがあったとき
  throw new MyError('エラー')
  // ...
} catch (err) {
  // instanceof でエラーの型を判定
  if (err instanceof MyError) {
    console.log('MyError')
  } else if (err instanceof Error) {
    console.log('その他のエラー')
  }
}

複数の場合も同じ感じです。

class MyError extends Error {
  constructor (msg) {
    super(msg)
  }
}

class MyErrorEx extends MyError {
  constructor (msg) {
    super(msg)
  }
}

try {
  // ...
  // ここでエラーがあったとき
  throw new MyError('エラー')
  // ...
} catch (err) {
  // instanceof でエラーの型を判定
  if (err instanceof MyErrorEx) {
    console.log('MyErrorExのエラー')
  } else if (err instanceof MyError) {
    console.log('MyErrorのエラー')
  } else if (err instanceof Error) {
    console.log('その他のエラー')
  }
}

エラー判定の注意点

ただし、instanceofの順番を間違えるとおかしなことになります。
MyErrorEx → MyError → Error
の順番で確認する必要があります。

なぜなら、以下を実行してみると分かりますが、継承したオブジェクトはinstanceofでtrueを返すからです。

const e = new MyErrorEx('hoge')
console.log(e instanceof MyErrorEx) // true
console.log(e instanceof MyError) // true
console.log(e instanceof Error) // true

この原則に気付かず、かなりハマってしまいましたので、皆さんもご注意を。

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?