async와 await를 통한 JS 에러 처리(error handling)

하유진·2021년 8월 20일
post-thumbnail

✔ 에러 처리(error handling)란?

  • 에러 Error
    : 메모리 부족, 스택오버플로우 등 프로그램 코드에 의해서 수습될 수 있는 심각한 오류. 발생시 프로그램이 비정상 종료된다.

  • 에러 처리 Error Handling:
    -> 프로그램 내에서 에러가 발생한 상황에 대해 대응하고 이를 복구하는 과정

Try Catch 문법

try {
  try_statements //실행될 선언들
}
[catch (exception_var) { //exception_var = catch 블록과 관련된 예외 객체를 담기 위한 식별자
  catch_statements //try블럭에서 예외가 발생했을 때 실행될 선언들
}]
[finally {
  finally_statements 
 //try 선언이 완료된 이후에 실행된 선언들. 이 선언들은 예외 발생 여부와 상관없이 실행된다.
}]

예시

function thisThrows() {
    throw new Error("Thrown from thisThrows()");
}

try {
    thisThrows();
} catch (e) {
    console.error(e);
} finally {
    console.log('We do cleanup here');
}

// Output:
// Error: Thrown from thisThrows()
//   ...stacktrace
// We do cleanup here

일반 에러를 throw하는 thisThrows()를 호출하면 이 에러를 catch하고 log할 수 있다. 그리고 finally 블록에서 선택적으로 어떤 코드를 실행할 것이다.

Try Catch와 거부된(Rejecting) Promise

thisThrows()를 async 함수로 만들어보자.

async function thisThrows() {
    throw new Error("Thrown from thisThrows()");
}

try {
    thisThrows();
} catch (e) {
    console.error(e);
} finally {
    console.log('We do cleanup here');
}

// output:
// We do cleanup here
// UnhandledPromiseRejectionWarning: Error: Thrown from thisThrows()

thisThrows()는 거부한 promise를 반환하고 일반 try...catch는 더이상 에러를 catch 할 수 없게 된다. thisThrows()가 async이기 때문에 우리가 이 함수를 호출할 때 thisThrows()는 promise를 보내고 코드는 더이상 기다리지 않는다. 따라서 finally 블록이 먼저 실행되고 그 후에 promise가 실행되고 reject된다.
이런 문제를 해결하는 방법에는 두 가지가 있다.

1. await 이용

thisThrows()를 async 함수 내에서 호출하고, await로 기다리게 한다.

async function thisThrows() {
    throw new Error("Thrown from thisThrows()");
}

async function run() {
    try {
        await thisThrows();
    } catch (e) {
        console.error(e);
    } finally {
        console.log('We do cleanup here');
    }
}

run();

// Output:
// Error: Thrown from thisThrows()
//   ...stacktrace
// We do cleanup here

2. catch 메소드 이용

thisThrows() 함수를 .catch() 호출과 함께 체이닝한다.


async function thisThrows() {
    throw new Error("Thrown from thisThrows()");
}

thisThrows()
    .catch(console.error)
    .then(() => console.log('We do cleanup here'));

// Output:
// Error: Thrown from thisThrows()
//   ...stacktrace
// We do cleanup here

정리

  • 동기 코드에서 try...catch를 사용할 수 있다.
  • 비동기 코드에서 에러를 해결할 때 .catch()와 try...catch(async함수와 결합하여) 사용할 수 있다.
  • promise를 try문에서 리턴할 때 try...catch 블록이 에러를 catch하길 원한다면 await을 이용
  • 에러를 감싸서 다시 throw할 때는 기존 에러의 스택 추적을 잃을 수 있다.
profile
Sungkyunkwan Univ. 20 @hau_jin_ #WEB #Pront-end #Back-end

0개의 댓글