본문 바로가기
Programing/Javascript

JavaScript Promise Error Handling

by 멍멍돌이야 2022. 7. 5.
반응형

Promise Error Handling

Promise를 반환하는 getUserById()라는 함수가 있다고 가정합니다.

function getUserById(id) {
    return new Promise((resolve, reject) => {
        resolve({
            id: id,
            username: 'admin'
        });
    });
}

 

Normal error

먼저 getUserById() 함수를 변경하여 promise 외부에서 오류를 발생시킵니다.

function getUserById(id) {
    if (typeof id !== 'number' || id <= 0) {
        throw new Error('Invalid id argument');
    }

    return new Promise((resolve, reject) => {
        resolve({
            id: id,
            username: 'admin'
        });
    });
}

둘째, then() 및 catch() 메서드를 모두 사용하여 약속을 처리합니다.

getUserById('a')
    .then(user => console.log(user.username))
    .catch(err => console.log(err));

 

코드에서 오류가 발생합니다.

Uncaught Error: Invalid id argument

프라미스 외부에서 예외를 발생시키면 try/catch로 잡아야 합니다.

try {
    getUserById('a')
        .then(user => console.log(user.username))
        .catch(err => console.log(`Caught by .catch ${error}`));
} catch (error) {
    console.log(`Caught by try/catch ${error}`);
}

Output:

Caught by try/catch Error: Invalid id argument

 

Errors inside the Promises

getUserById() 함수를 변경하여 promise 내부에 오류를 발생시킵니다.

let authorized = false;

function getUserById(id) {
    return new Promise((resolve, reject) => {
        if (!authorized) {
            throw new Error('Unauthorized access to the user data');
        }

        resolve({
            id: id,
            username: 'admin'
        });
    });
}

그리고 약속을 소비하십시오:

try {
    getUserById(10)
        .then(user => console.log(user.username))
        .catch(err => console.log(`Caught by .catch ${error}`));
} catch (error) {
    console.log(`Caught by try/catch ${error}`);
}

Output:

Caught by .catch Error: Unauthorized access to the user data

Promise 내부에 오류가 발생하면 try/catch가 아니라 catch() 메서드가 오류를 catch합니다.

약속을 연결하면 catch() 메서드는 모든 약속에서 발생한 오류를 포착합니다. 예를 들어:

promise1
    .then(promise2)
    .then(promise3)
    .then(promise4)
    .catch(err => console.log(err));

이 예에서 promise1, promise2 또는 promise4에 오류가 있으면 catch() 메서드가 이를 처리합니다.

 

Calling reject() function

오류를 던지는 것은 다음 예제와 같이 reject()를 호출하는 것과 같은 효과를 냅니다.

let authorized = false;

function getUserById(id) {
    return new Promise((resolve, reject) => {
        if (!authorized) {
            reject('Unauthorized access to the user data');
        }

        resolve({
            id: id,
            username: 'admin'
        });
    });
}

try {
    getUserById(10)
        .then(user => console.log(user.username))
        .catch(err => console.log(`Caught by .catch ${err}`));
} catch (error) {
    console.log(`Caught by try/catch ${error}`);
}

이 예에서 우리는 promise 내부에 오류를 던지는 대신에 reject()를 명시적으로 호출했습니다. catch() 메서드는 이 경우에도 오류를 처리합니다.

 

Missing the catch() method

다음 예제에서는 promise 내부의 오류를 처리하기 위한 catch() 메서드를 제공하지 않습니다. 런타임 오류가 발생하고 프로그램이 종료됩니다.

function getUserById(id) {
    return new Promise((resolve, reject) => {
        if (!authorized) {
            reject('Unauthorized access to the user data');
        }
        resolve({
            id: id,
            username: 'admin'
        });
    });
}

try {
    getUserById(10)
        .then(user => console.log(user.username));
    // the following code will not execute
    console.log('next');

} catch (error) {
    console.log(`Caught by try/catch ${error}`);
}

Output:

Uncaught (in promise) Unauthorized access to the user data

약속이 해결되면 catch() 메서드를 생략할 수 있습니다. 앞으로 잠재적인 오류로 인해 프로그램이 예기치 않게 중지될 수 있습니다.

 

Summary

  • Promise 내에서 catch() 메서드는 throw 문과 reject()로 인해 발생한 오류를 포착합니다.
  • 오류가 발생하고 catch() 메서드가 없으면 JavaScript 엔진은 런타임 오류를 발생시키고 프로그램을 중지합니다.

 

 

 

 

 

Reference: https://www.javascripttutorial.net/es6/promise-error-handling/

 

728x90
반응형

댓글