LoginSignup
1
0

More than 3 years have passed since last update.

[JavaScript]エラーをthrowする場合はちゃんとカスタムエラーを作ろう

Last updated at Posted at 2020-07-04

エラーをthrowする際は、カスタムエラーを定義してあげましょう。
例えば、意図して処理をスルーさせている場合は、コメントではなくカスタムエラーでやったほうがより良いコードとなります。(併用もOK)

class GetUser404Error extends Error {};

function getUser(id) {
  try {
    return userService.getUser(id):
  } catch(e) {
    if (e.status === 404) {
      throw new GetUser404Error();
    }
     throw e;
  }
}

try {
  getUser(123);
  // ...
} catch(e) {
  // データが取得できない場合は、エラーを表示せずに処理を終える
  if (e instanceof GetUser404Error) {
    return;
  }
  errorDialog(e.message);
}

参考

1
0
2

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