Skip to content

UnhandledPromiseRejectionWarning inside .map #3030

@Piranit

Description

@Piranit

Bug Report

Current behavior

I have a simple route '/err'. It has logic where appear BadRequestException.
Since I have HttpExceptionFilter this BadRequestException should be caught by HttpExceptionFilter.
But when I use .map() function to iterate an array HttpExceptionFilter not catch this error and I have UnhandledPromiseRejectionWarning.

Not Working Code

@Get('err')
@UseFilters(new HttpExceptionFilter())
async err() {
    console.log(`err`);
    const numbers: number[] = [1];
    const res = numbers.map(async x => await this.test(x));
    return res;
}

async test(n: number) {
    return new Promise((resolve, reject) => {
        throw new BadRequestException('wrong number');
        resolve(n);
    });
}

Server Logs

(node:25899) UnhandledPromiseRejectionWarning: Error: [object Object]
(node:25899) 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(). (rejection id: 2)
(node:25899) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Possible Solution

But when I iterate array with for loop and not use .map() HttpExceptionFilter successfully catches this error I didn't have UnhandledPromiseRejectionWarning.

Working Code

@Get('err')
@UseFilters(new HttpExceptionFilter())
async err() {
    console.log(`err`);
    const numbers: number[] = [1];
    const res = [];
    for (let i = 0; i < numbers.length; i++) {
        res.push(await this.test(numbers[i]));
    }
    return res;
}

async test(n: number) {
    return new Promise((resolve, reject) => {
        throw new BadRequestException('wrong number');
        resolve(n);
    });
}

Problem

So why there appear UnhandledPromiseRejectionWarning when I use .map() and not appear when I use for loop instead?

Environment

[System Information]
OS Version     : Linux 4.15
NodeJS Version : v10.16.3
NPM Version    : 6.9.0
[Nest Information]
platform-express version : 6.0.0
swagger version          : 3.1.0
typeorm version          : 6.1.3
common version           : 6.7.0
core version             : 6.7.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    needs triageThis issue has not been looked into

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions