Catching exceptions with async await and avoid unhandledRejection [duplicate]

I have a larger use case that I narrowed down to the following code snippet.
This code might not make a lot of sense however this is just to demonstrate the issue I have.
I am trying to catch the exception thrown by a function (below called throwFunction).
I want to call the function but not wait for it to complete even though it returns a promise.
Directly after calling the function I call another async function (waitALittle).
I want to be able to catch any exception within the try catch.
The problem I see is that I cant seem to catch the thrown error and get unhandledRejection .
I tried surrounding almost every single piece of code with try catch but nothing works. I always get unhandled rejection.
Below is the output you see the unhandledRejection occurs in between the start and end of the waitFunction and that seems to be the core of the problem, when an exception is thrown while another function is still not resolved its promise.

questions.

  1. why is this happening, why doesnt the try catch block, catch the exception.
  2. How can this be fixed.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const setTimeout = require ('timers/promises').setTimeout;
async function waitALittle(){
await setTimeout(100);
}
async function throwFunction(a){
//do some stuff...
throw new Error('test');
}
async function f(){
try {
throwFunction();
console.log('wait started')
await waitALittle();
console.log('wait ended')
}catch(e) {
console.log('exception caught');
}
}
process.on('unhandledRejection', ()=>{
console.log('unhandledRejection event');
})
f();
</code>
<code>const setTimeout = require ('timers/promises').setTimeout; async function waitALittle(){ await setTimeout(100); } async function throwFunction(a){ //do some stuff... throw new Error('test'); } async function f(){ try { throwFunction(); console.log('wait started') await waitALittle(); console.log('wait ended') }catch(e) { console.log('exception caught'); } } process.on('unhandledRejection', ()=>{ console.log('unhandledRejection event'); }) f(); </code>
const setTimeout = require ('timers/promises').setTimeout;

async function waitALittle(){
    await setTimeout(100);
}

async function throwFunction(a){
//do some stuff...
throw new Error('test');
}

async function f(){
    try {
        throwFunction();
        console.log('wait started')
        await waitALittle();
        console.log('wait ended')
    }catch(e) {
        console.log('exception caught');
    }
}

process.on('unhandledRejection', ()=>{
    console.log('unhandledRejection event');
})

f();

Output:
wait started
“unhandledRejection event”
wait ended

I tried to cover many parts of the code with try catch but nothing caught the exception and I continued to get unhandledRejection.

New contributor

ryan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

For the try/catch to work on throwFunction, you are missing await in front of the call to throwFunction:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>async function f(){
try {
await throwFunction(); // <<< here
console.log('wait started')
await waitALittle();
console.log('wait ended')
}catch(e) {
console.log('exception caught');
}
}
</code>
<code>async function f(){ try { await throwFunction(); // <<< here console.log('wait started') await waitALittle(); console.log('wait ended') }catch(e) { console.log('exception caught'); } } </code>
async function f(){
    try {
        await throwFunction(); // <<< here
        console.log('wait started')
        await waitALittle();
        console.log('wait ended')
    }catch(e) {
        console.log('exception caught');
    }
}

Without it, the function runs asynchronously in parallel with the rest of the code. The error it throws results in the promise returned from the synchronous throwFunction() call being rejected eventually. However you don’t use that promise for anything, and in particular no .catch is called on it (not even implicitly using await), so the rejection is unhandled.

Now, you said you don’t want to wait for it. In this case, you would need to handle exceptions on it separately using .catch:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>async function f(){
try {
throwFunction().catch(e => {
console.log('async exception caught');
});
console.log('wait started')
await waitALittle();
console.log('wait ended')
}catch(e) {
console.log('exception caught');
}
}
</code>
<code>async function f(){ try { throwFunction().catch(e => { console.log('async exception caught'); }); console.log('wait started') await waitALittle(); console.log('wait ended') }catch(e) { console.log('exception caught'); } } </code>
async function f(){
    try {
        throwFunction().catch(e => {
            console.log('async exception caught');
        });
        console.log('wait started')
        await waitALittle();
        console.log('wait ended')
    }catch(e) {
        console.log('exception caught');
    }
}

In this situation, being able to catch it within the outer try would not even make sense as throwFunction may throw after your other code isn’t even inside of the try anymore.

If you just want to wait for both functions in parallel, though, so you continue once both are done, then it’s possible again, using Promise.all:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>async function f(){
try {
await Promise.all([
throwFunction(),
(async () => {
console.log('wait started')
await waitALittle();
console.log('wait ended')
})()
]);
}catch(e) {
console.log('exception caught');
}
}
</code>
<code>async function f(){ try { await Promise.all([ throwFunction(), (async () => { console.log('wait started') await waitALittle(); console.log('wait ended') })() ]); }catch(e) { console.log('exception caught'); } } </code>
async function f(){
    try {
        await Promise.all([
            throwFunction(),
            (async () => {
                console.log('wait started')
                await waitALittle();
                console.log('wait ended')
            })()
        ]);
    }catch(e) {
        console.log('exception caught');
    }
}

(That async IIFE could be replaced with simply waitALittle() if it weren’t for the console.log statements.)

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật