問題一覧に戻る
中級async
問題96: try-catch-finally
async/awaitのエラー処理を学びましょう。非同期関数内でtry-catch-finallyを使用すると、Promiseのthen/catch/finallyと同じように、エラーハンドリングとクリーンアップ処理を同期的な構文で記述できます。tryブロックで非同期処理を実行し、catchブロックでエラーを捕捉し、finallyブロックで成功・失敗に関わらず実行される後処理を記述します。これにより、エラー処理が直感的になり、コードの可読性が向上します。
async function riskyOperation(shouldFail) {
if (shouldFail) {
throw new Error("操作が失敗しました");
}
return "成功";
}
async function main() {
{
const result = await riskyOperation(false);
console.log(result);
const failed = await riskyOperation(true);
console.log(failed);
} (error) {
console.error(`エラーをキャッチ: ${error.message}`);
} {
console.log("クリーンアップ実行");
}
}
main();