동기적 예외처리
첫번째,
function sum(x, y) {
if (typeof x !== "number" || typeof y !== "number") {
throw "숫자가 아닙니다";
}
return x + y;
}
console.log(sum("a", 2)); // 숫자가 아닙니다.
두번째,
// "will: f1";
// "f1 start";
// "f2 start";
// "f2 end";
// "f1 end";
// "did: f1";
function f2() {
console.log("f2 start");
console.log("f2 end");
}
function f1() {
console.log("f1 start");
f2();
console.log("f1 end");
}
console.log("will: f1");
f1();
console.log("did: f1");
// "will: f1";
// "f1 start";
// "f2 start";
// Error: '에러'
// "f1 end";
// "did: f1";
function f2() {
console.log("f2 start");
throw new Error("에러");
console.log("f2 end");
}
function f1() {
console.log("f1 start");
try {
f2();
} catch (e) {
console.log(e);
}
console.log("f1 end");
}
console.log("will: f1");
f1();
console.log("did: f1");
비동기적 예외처리
Promise / Catch
function wait(sec) {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject("error!");
}, sec * 1000);
});
}
wait(3).catch((e) => {
console.log("1st catch", e); // '1st catch' 'error!'
});
// 첫번째
// then처럼 계속 호출시 두번째 catch가 출력 안됨
// 보톹 객체의 체인은 같은 객체를 바라보는데 첫번째 catch는 위에 promise의 함수를 바라보고 두번째 catch는 첫번째 catch를 바라봄
// 띠라서 첫번째 catch가 에러를 잡아내서 두번쨰 catch에서는 예외가 발생하지 않아 작동 안됨
wait(3)
.catch((e) => {
console.log("1st catch", e); // '1st catch' 'error!'
// throw e; 추가하면 두번째 '2nd catch' 'error!' 출력
})
.catch((e) => {
console.log("2nd catch", e);
});
// 두번째
// then을 사용
wait(3)
.then(
() => {
console.log("done!!");
},
(e) => {
console.log("1st catch in Then", e); // "1st catch in Then"
}
)
.catch((e) => {
console.log("2nd catch", e); // 첫번째와 동일한 이유로 출력 안됨
});
Async / Await
// 첫번째
async function myAsyncFun() {
throw "myAsyncError";
}
function myPromiseFun() {
return new Promise((resolve, reject) => {
reject("myError!");
});
}
const result1 = myAsyncFun().catch((e) => {
console.log(e); // "myAsyncError"
});
const result2 = myPromiseFun().catch((e) => {
console.log(e); // "myError!"
});
// 두번째
function wait(sec) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("done!");
reject("wait Error");
}, sec * 1000);
});
}
// resolve 일때
// async function myAsyncFun() {
// console.log(new Date()); // 2021-06-25T20:39:30.029Z
// await wait(3); // 3초 뒤에
// console.log(new Date()); // 2021-06-25T20:39:30.029Z
// }
// const result = myAsyncFun();
//reject 일때
async function myAsyncFun() {
console.log(new Date()); // 2021-06-25T20:39:30.029Z
//await wait(3).catch(e => {console.error(e);}); 이렇게 해도됨
try {
await wait(3); // 3초 뒤에
} catch (e) {
console.error(e); // wait Error
}
console.log(new Date()); // 2021-06-25T20:39:30.029Z
}
const result = myAsyncFun();
//reject 일때
// 이렇게 해도됨
async function myAsyncFun() {
console.log(new Date()); // 2021-06-25T20:39:30.029Z
// 선언해서 위에서 resolve일 경우 출력되나 reject일 경우 undefined가 나옴
// const result = await wait(3).catch((e) => {
// console.error(e);
// });
// console.log(result);
await wait(3).catch((e) => {
console.error(e);
});
console.log(new Date()); // 2021-06-25T20:39:30.029Z
}
const result = myAsyncFun();