Reject в Promise вызывает ошибку, хотя код правильный?

Рейтинг: 0Ответов: 1Опубликовано: 20.01.2023

Почему при выполнении данного кода возникает ошибка:

[UnhandledPromiseRejection: 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(). The promise rejected with the reason "#<Object
>".] {
  code: 'ERR_UNHANDLED_REJECTION'
}

Код:

const axios = require('axios');

(async () => {
    const get_login_and_password = () => {
        return new Promise((resolve, reject) => {
            let res = {
                success: false
            }

            axios
                .get('http://test.site/index.php', {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                .then((response) => {
                    if (response.data?.email && response.data?.password) {
                        res.success = true
                        res.email = response.data.email
                        res.password = response.data.password
                    } else {
                        res.message = 'Nothing data: EMail and password!'
                    }
                })
                .catch((e) => {
                    res.message = e.message
                })
                .finally(() => {
                    if (res.success) {
                        resolve(res)
                    } else {
                        reject(res)
                    }
                })
        })
    }

    console.log(await get_login_and_password())
})()

Всем спасибо!

Ответы

▲ 0Принят

Надо просто обработать reject с помощью catch

console.log(await get_login_and_password().catch(e => e))

Можно так же обрабатывать reject в then во втором параметре:

console.log(await get_login_and_password().then(
    res => {
        // Обработчик события resolve
    }, 
    rej => {
        // Обработчик события reject
    })
);

Если есть необработанный reject вы и получаете ошибку UnhandledPromiseRejection