본문 바로가기

Error

[Error] UnhandledPromiseRejection

728x90

Node를 사용하면서 async/await 구문을 사용하여 Promise를 처리하는 방법에 대한 예제를 만들던 중에 UnhandledPromiseRejection가 발생하였습니다.

 

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To termin ate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodej s.org/api/cli.html#cli_unhandled_rejections_mode).

 

async 함수를 사용하는데 try~catch block으로 감싸지 않았거나 .catch로 처리하지 않은 reject가 있을 때 발생한다고 되어 있습니다. 따라서 error가 발생하는 원인은 다음과 같습니다.

 

  1. async 함수를 try~catch 구문으로 error 처리를 하지 않은 경우
  2. 반환되는 promise에서 .catch로 reject 처리를 하지 않은 경우

각각의 해결 방법은 다음과 같습니다. 우선 첫 번째 문제에 대한 해결방법입니다.

 

async function asyncCallDoubleReject() {
    try{
        const result = await promiseFunction();
    } catch (e) {
        console.error(e);
    }
}

 

await가 있는 명령줄을 모두 try~catch 구문 안에 넣습니다.

 

다음은 두번째 문제에 대한 해결방법입니다.

 

function promiseFunction() {
    return new Promise((resolve, reject) => {
        reject('첫번째 실패');
    }).catch((error) => {
        return error;
    });
}

 

await를 통해 반환되는 Promise의 .catch에 대한 처리를 추가해줍니다.

728x90