dmerlea
dmerlea

Reputation: 936

NestJS crashing on throwing http exception

main.controller.ts:135
throw new NotFoundException('Swap not found');
^
NotFoundException: Swap not found

I have a pretty simple request in a controller

@Get("/details")
@ApiResponse({
    status: 200,
    description: 'Returns the details',
})
async getDetails(
    @Query('id') id: string
): Promise<Result> {
    let details = await this.databaseService.find(id)
    if (!details) {
        throw new NotFoundException('Swap not found');
    }
    return {
        details: details,
    }
}

After the exception is thrown, NestJS also stops from running!? How do I avoid this? I know about the exception filters, but that's for custom exceptions, right? I use a default one.

Still, just in case, I've added a global one to test and same behaviour: app.useGlobalFilters(new HttpExceptionFilter());

Is this an expected behavior?

Upvotes: 4

Views: 4097

Answers (3)

Richard Fernandez
Richard Fernandez

Reputation: 599

Make sure you return your expection throw from the controller otherwise the api gives you the connection error

@Get("/details")
@ApiResponse({
    status: 200,
    description: 'Returns the details',
})
async getDetails(
    @Query('id') id: string
): Promise<Result> {
    let details = await this.databaseService.find(id)
    if (!details) {
        // Add the return here!
        return throw new NotFoundException('Swap not found');
    }
    return {
        details: details,
    }
}

Upvotes: -1

You might want to check the function inside your service file,and await the responses properly before returning it.

Upvotes: 2

Rami Osman
Rami Osman

Reputation: 187

I faced the same issue, I fixed it by awaiting for the task to be done before throwing, I threw an error after sending the response, so I just added an await in my service where it is required.

Upvotes: 9

Related Questions