Skip to content

Instantly share code, notes, and snippets.

@adhrinae
Last active July 6, 2019 10:48
Show Gist options
  • Save adhrinae/8b2cb0be3992194afd217b6a52d08128 to your computer and use it in GitHub Desktop.
Save adhrinae/8b2cb0be3992194afd217b6a52d08128 to your computer and use it in GitHub Desktop.
Better error handling with async/await

async / await 과 함께하는 조금 더 깔끔한 에러 핸들링

async function loginController() {
  try {
    const a = await loginService().catch(error => {
      throw new CustomErrorHandler({ code: 101, message: 'a failed', error: error });
    });
    const b = await someUtil().catch(error => {
      throw new CustomErrorHandler({ code: 102, message: 'b failed', error: error });
    });
    //someoeeoe
    if (a && b) console.log('no one failed');
  } catch (error) {
    if (!(error instanceof CustomErrorHandler)) {
      console.log('gen error', error);
    }
  }
}
function loginService() {
  return new Promise((resolve, reject) => {
    resolve('hahaha');
    //reject("nonono");
  });
}

loginController();

function someUtil() {
  return new Promise((resolve, reject) => {
    resolve('hahah');
    reject('nonono');
  });
}

function CustomErrorHandler(someObject) {
  console.log(someObject);
}

try / catch 의 중첩을 줄일 수 있을 뿐만 아니라 Promise.all 의 제약 사항 중 하나인 reject가 하나라도 나오면 바로 다 실패처리된다 는 문제를 극복할 수 있다.
저렇게 처리된 Promise 객체들은 Promise.all 로 처리했을 때 에러가 발생할 경우 resolve된 에러가 배열의 요소로 담겨 나올 것이기 때문

@khg0712
Copy link

khg0712 commented Jul 6, 2019

loginController의 catch문의 gen error은 무슨 의미인가요?

@adhrinae
Copy link
Author

adhrinae commented Jul 6, 2019

@khg0712

'Generate Error' 를 대충 줄여서 썼던걸로 기억합니다

@khg0712
Copy link

khg0712 commented Jul 6, 2019

@adhrinae
좋은 코드 공유해주셔서 감사합니다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment