Tips for resolving uncaught promise rejection alerts on NestJS

I'm currently utilizing NestJS for the backend of my Angular project, and I encountered an issue after installing Swagger. Prior to the installation, everything was running smoothly. However, post-installation, a warning about an unhandled promise rejection surfaced, preventing the application from running.

If I comment out the code in the controllers, the application works fine leading me to suspect there may be an issue with async/await. Unfortunately, I am unsure about how to address this problem. Therefore, any assistance or suggestions on resolving this would be greatly appreciated.

Controller

    @Put(':id')
    async updateHelpSubsection(@Body() newHelp: HelpSubsectionModule, @Param() params): Promise<HelpSubsectionModule> {
        try{
            let oldHelpData = await this.helpSubsectionService.getHelpSubsectionbyId(params.id)
            return this.helpSubsectionService.updateHelpSubsection(oldHelpData, newHelp);
        }catch(e) {
            console.log(e)
        }
    }

Services

    async updateHelpSection(updateHelp: HelpSectionEntity, newHelpData): Promise<HelpSectionEntity> {

        Object.keys(newHelpData).forEach((key) => {
            updateHelp[key] = newHelpData[key];
        });

        try {
            return await this.helpSectionRepo.save(updateHelp);
        } catch (err) {
            throw new HttpException({
                error: err
            }, HttpStatus.FORBIDDEN)
        }
    }

This is the warning message I'm encountering: https://i.sstatic.net/wDECV.png

Answer №1

In the quest for a solution to manage errors that haven't been handled, try out this method:

process.on('unhandledRejection', (error) => {
    console.log('handle the error...');
});

Answer №2

Kindly make the necessary adjustments in the controller:

       @Put(':id')
       async updateHelpSubsection(@Body() newHelp: HelpSectionEntity, @Param() params): Promise< HelpSectionEntity> {
           try{
               let oldHelpData = await this.helpSubsectionService.getHelpSubsectionbyId(params.id)
               return this.helpSubsectionService.updateHelpSubsection(oldHelpData, newHelp);
           }catch(e) {
               console.log(e)
           }
       }

It is important to note that modules are not permitted in TypeScript types.

Kindly substitute HelpSubsectionModule with HelpSectionEntity.

Answer №3

Unsure about the functioning of @Put(:id), however, updateHelpSection does provide a promise that needs to be managed using .then() to retrieve data upon successful resolution and catch() to handle errors in case of rejection. For further information, refer to this insightful article

Answer №4

Remember, what you are seeing here is simply a reminder of best practices.

It's important for every Promise to have error handling in place when making requests.

For instance:

Take this Promise as an example.

const slowAndSteady = new Promise(function(resolve, reject) {
    reject();
});

If you utilize async/await in the following manner.

(async function() {
    await slowAndSteady();
})();

You may encounter an UnhandledPromiseRejectionWarning, but by employing it like this.

slowAndSteady
    .then(function(result) {
        console.log('result', result);
    })
    .catch(function(err) {
        console.log('error: ', err);
    });

The warning will disappear.

In case you still wish to use async/await, you have two options.

(async () => {
  try {
    const result = await slowAndSteady();
    console.log('result', result);
  } catch(e) {
    console.log('Error caught',e);
  }
})();

Alternatively,

(async () => {
  const result = await slowAndSteady().catch((e) => console.log('Error caught',e));
  console.log('result', result);
})();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Uploading files using Angular 2 and TypeScript

I am currently developing an Angular 2 project, where I need to upload a file and send some parameters from the client to the server (Spring Rest Server). I have attempted to use the FormData Interface for this purpose. However, when I try to append a file ...

Using TypeScript to bypass rest properties in React

Enhanced for TypeScript 2.1 Exciting news! TypeScript 2.1 now fully embraces object spread/rest functionality making workarounds a thing of the past! The Original Inquiry Incorporating JSX spread attributes in React to pass HTML properties from a comp ...

Using the pipe feature in Angular 2, we can easily filter an object

I have a query: export class Task { public id: number; public title: string; public isDone: boolean; public createdDate: Date; public assignedTo: string; } A method: fetchTasks(): Observable < Task[] > { return thi ...

Failing to reach the nested if statements within a switch case block

Before removing my question, please read this. Despite testing with console.logs, my code does not enter the if statements. I have not come across a similar solution to my issue. In an attempt to address any timing or asynchronous problems, I added a use ...

The object may be null

Is there a way to verify if an object is null? let hostels = null; if (hostels[0] !== null && hostels[0].name !== null) { } However, I encountered the following error: error TS2531: Object is possibly 'null'. ...

Troubles in app.module arise post-transition from Angular 15 to Angular 16

While attempting to upgrade my Angular application from version 15 to 16, I ran into a multitude of errors within my app.module. Despite trying various troubleshooting steps, such as checking module imports and utilizing ng update, the errors persist. It a ...

Angular6 - accessing elements that are not visible on the page

Currently, I am facing a situation where I have a component embedded in my HTML template that needs to remain hidden until a certain condition is met by checking a box. The tricky part is that the condition for setting "showControl" to true relies on calli ...

TypeScript - Functionally Speaking

When defining a function type, the example below does not allow the use of const interface Square{ readonly color: string; readonly area: number; } interface compareTo{ (const v1: Square, const v2: Square): number; // syntax error } I ...

Issue with SignalR client functionality following update to .NET Core 3.1版本

Upon updating our server-side code to asp.net core 3.1, we encountered an issue with the javascript client for signalr (@microsoft/signalr 3.1.0). The errors we are facing are: https://i.sstatic.net/ITZyK.png Here is the code snippet for the hub initial ...

Tips on preventing the copying of .txt and .xml files with the fs-extra.copySync function

Currently, I am working on a small TypeScript assignment and facing an issue that I can't seem to solve. Any guidance or advice on the problem mentioned below would be greatly appreciated. The task at hand involves copying a directory from one locati ...

Leveraging Aliases in Nuxt 3 Configuration: Unleashing the Power of Aliases in your Config File

Encountering an error while attempting to import files using aliases in the configuration file (nuxt.config.ts): Cannot find module '~/.... For reference, please check out this example: codesnadbox.io Showcasing a Short Example nuxt.config.ts import ...

Scriptwriter: Module not found

I am encountering an issue where I have a class named 'Button' and I am attempting to import it into my example.spec.ts file. Despite not receiving any errors from the compiler, when I run the test, an error is thrown: Error: Cannot find module ...

A guide on retrieving TypeScript mongoose/typegoose schema

Here is a defined schema for an account class AccountSchema; Below is the model declaration for the account const AccountClass: Model<AccountSchema & Document>; class Account extends AccountClass; Why isn't this functioning as expected? ...

What is the reasoning behind defaultValue possessing the type of any in TextField Material UI?

According to the Material UI guidelines, the component TextField specifies that its defaultValue property accepts the type any. I decided to experiment with this a bit and found that in practice, defaultValue actually supports multiple types. You can see ...

Tips for implementing row span for an entire column in a custom column within an Angular Material table

I have customized a column for my angular-material table, but I am struggling to apply row span for the entire column as all cells in that column have the same data. I have made modifications to the project by adding a custom vendor number column, where th ...

Blocked: Stripe Connect Embedded Onboarding Popup

I have been diligently following the steps in the tutorial to set up Onboarding with Stripe Connect, which can be found at the following link: After completing all the necessary setup, I encountered an issue where the iFrame containing the "Add Informatio ...

Describing the implementation of UNO out parameters within definitions

The UNO API offers support for inout and out parameters. In this scenario, a variable is passed into a function, the function modifies the variable, and the updated value of the variable can be accessed outside the function. Javascript lacks native suppor ...

The file or directory does not exist: ENOENT error when trying to lstat '/Users/Desktop/node_modules'

There was an unexpected issue that occurred: ENOENT: no such file or directory, lstat '/Users/Desktop/node_modules' See "/private/var/folders/3p/l_k1wk8n76v3cfwnxk0blx000000gn/T/ng- DF5EZ7/angular-errors.log" for more information. Ev ...

Assign a predetermined value to a dropdown list within a FormGroup

I have received 2 sets of data from my API: { "content": [{ "id": 1, "roleName": "admin", }, { "id": 2, "roleName": "user", }, { "id": 3, "roleName": "other", } ], "last": true, "totalEleme ...

Displaying user input data in a separate component post form submission within Angular

I recently developed an employee center app with both form and details views. After submitting the form, the data entered should be displayed in the details view. To facilitate this data transfer, I created an EmployeeService to connect the form and detail ...