🟨 JavaScript/개념

[드림코딩] 콜백함수 (3) : promise로 Error Handling하기 (reject, catch 활용)

Zoeeey 2022. 10. 4. 17:24

Error Handling

const turnonLaptop = () =>
  new Promise((resolve, reject) => {
    setTimeout(() => resolve(`노트북 실행.`), 1000);
  });
const loginBlog = blog =>
  new Promise((resolve, reject) => {
    setTimeout(() => reject(new Error(`Error! ${blog} => 블로그 진입.`)), 1000);
  });
const writePost = post =>
  new Promise ((resolve, reject) => {
    setTimeout(() => resolve(`${post} => 게시 완료.`), 1000);
  });

producer 코드를 작성했다.

turnOnlaptop() //
  .then(openBlog)
  .then(writePost)
  .then(console.log);
  
 // VM86:7 Uncaught (in promise) Error: Error! 노트북 실행. => 블로그 진입.

then만 붙이면 이렇게 openBlog에서 reject된 에러를 catch하지 못해 uncaught Error가 난다.

turnonLaptop() //
  .then(loginBlog)
  .catch(error => {
    return `비밀번호 찾기`;
  })
  .then(writePost)
  .then(console.log)
  .catch(console.log);
  
  // 비밀번호 찾기 => 게시 완료.

catch를 사용하면 내가 원하는 곳에서 error를 handling할 수 있다.


출처 : 드림코딩 https://www.youtube.com/@dream-coding / MDN https://developer.mozilla.org/ko/