LoginSignup
0
0

More than 1 year has passed since last update.

【javascript】例外処理, try

Posted at

例外処理

エラーが発生した時に飛ぶ特別な処理

tryの基礎構文

try { //try直下の構文に何らかのerrorが発生したらcatch処理へ
    console.log('start') 
    throw new Error('error message');
    console.log('end')
} catch(e){
    console.error(e);
} finally { //終了処理は必ず通る。
    console.log('bye')
}

case

  • 取得したいjsonファイルが空だったらerrorを出力する
async function fetchUsers(){
    const response = await fetch('users.json')
    if(response.ok){ //responseには成功可否を判断するokプロパティが存在する。
        const json = await response.json(); //jsonファイルにアクセス。
        if(!json.length){ //jsonデータが空だったらtrue
            throw new Error('no data found')
        }
    return json;
    }
}


async function init(){
    try {
        const users = await fetchUsers(); //上で作成した関数を実行
        for(const user of users){
        console.log(`私は ${user.name}, ${user.age} 才です。`)
        }
    }catch(e){ //errorが飛んできたらここを処理
        console.error(e);
    } finally { //終了処理は必ず行う
        console.log('bye')
    }
}

init();

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