LoginSignup
0
1

More than 1 year has passed since last update.

【JavaScript】非同期処理⑨ 例外処理とエラー

Posted at

はじめに

Udemyの【JS】ガチで学びたい人のためのJavaScriptメカニズムの講座の振り返りです。

前回の記事

目的

  • 非同期処理についての理解を深める

本題

1.例外処理とエラー

例外処理とはなにかエラーが発生した際に飛ぶ特別な処理のこと

基本構文

try{
  throw new Error();
} catch(e) {
  // エラーハンドリング
} finally {
  // 終了処理
}

例1

基本的な使い方

main.js
// 動かしたいコードをtryの中に記述していく
try{
  console.log("start");
  // エラーを出力する → catchに移行する
  throw new Error("error message");
  // 上記で処理がcatchに移行するので下記endは出力されない
  console.log("end")
} catch(e) {
  console.error(e);
} finally {
  // 出力される終了処理
  console.log('bye');
}

上記の出力結果は以下の通り

console.
start
> Error: error message
    at main.js:5
bye

例2

さらに実践的な使い方

前提

jsonファイルからデータを引っ張ってくるがあえてここではからにしておく(エラーを出すため)

user.json
[

]
main.js
async function fetchUsers() {
  const response = await fetch('users.json');
  const json = await response.json();
  return json;
}


async function init(){
  const users = await fetchUsers();
  for(const user of users) {
      console.log(`I'm ${user.name}, ${user.age} years old`)
  }
}

init();

user.jsonファイルが空欄なので何も出力されていないが、ここにエラーを表示する

async function fetchUsers() {
  const response = await fetch('users.json');
  // 条件分岐でデータがうまく渡っている場合そうでない場合で分ける
  if (response.ok){
    const json = await response.json();
    // ここでjsonファイルが0だった場合にthrowでエラー処理をcatchに移行したい
    // jsonファイルのlength(配列の長さ)が0だった場合falseなので!演算子でtrueにする
    if(!json.length){
      throw new Error("no data found")
    }
    return json;
  } 
}

async function init(){
  // 上記の内容をtryで捌く
  try {
    const users = await fetchUsers();
    for(const user of users) {
        console.log(`I'm ${user.name}, ${user.age} years old`)
    }
  }catch(e){
    // ここでthrowを受けることでno data foundとエラー表示される
    console.error(e);
  }finally{
    // 終了処理はどちらにせよ出力される
    console.log('bye');
  }
}

init();

例3

カスタムエラーに関して

async function fetchUsers() {
  const response = await fetch('users.json');
  if (response.ok){
    const json = await response.json();
    if(!json.length){
      // ここでNoDataErrorを出力できるようにする
      throw new NoDataError("no data found")
    }
    return json;
  } 
}

// Errorを継承
// 条件分岐でエラーを出力したい場合に行う
class NoDataError extends Error {
  constructor(message){
    super(message);
    this.name = `NoDataError`;
  }
}

async function init(){
  try {
    const users = await fetchUsers();
    for(const user of users) {
        console.log(`I'm ${user.name}, ${user.age} years old`)
    }
  }catch(e){
    console.error(e);
  }finally{
    console.log('bye');
  }
}

init();

今日はここまで!

参考にさせて頂いた記事

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